-----------------------------------------------------
-- Export file for user TBICDS                     --
-----------------------------------------------------

prompt
prompt Creating table APP_MENU_ITEMS
prompt =============================
prompt
create table TBICDS.APP_MENU_ITEMS
(
  ITEM_ID            NUMBER,
  ITEM_TITLE         VARCHAR2(255),
  ICON_CLS           VARCHAR2(48),
  ICON_FILE          VARCHAR2(128),
  HREF               VARCHAR2(128),
  HREF_TARGET        VARCHAR2(128),
  HANDLER            VARCHAR2(255),
  DIRECT_EVENT       VARCHAR2(255),
  PARENT_ITEM        NUMBER default 0,
  TARGET_APP         NUMBER default 1,
  USER_TYPE          NUMBER,
  USER_RIGHTS        NUMBER,
  SELECTED_OPTS      NUMBER,
  CLOSES_PATIENT     NUMBER default 0,
  IS_SEPARATOR       NUMBER default 0,
  SORT_ORDER         NUMBER,
  ALTERNATE_LANGUAGE VARCHAR2(255),
  ACTIVE             NUMBER default 1,
  ITEM_TYPE          NUMBER default 1,
  IDENTIFIER         VARCHAR2(64),
  REQUIRES_PATIENT   NUMBER
)
;
comment on table TBICDS.APP_MENU_ITEMS
  is 'Contains information related to application menu items';
comment on column TBICDS.APP_MENU_ITEMS.ITEM_TYPE
  is '1:MenuItem, 2:ToolbarSeparator, 4:ToolbarFill';
comment on column TBICDS.APP_MENU_ITEMS.REQUIRES_PATIENT
  is '1:yes 0:no';

prompt
prompt Creating table APP_USER
prompt =======================
prompt
create table TBICDS.APP_USER
(
  EMAIL                VARCHAR2(50),
  UIDPWD               VARCHAR2(200),
  RANK                 VARCHAR2(10),
  NAME                 VARCHAR2(50) not null,
  PROVIDER_ID          VARCHAR2(50) not null,
  MILITARY_SERVICE_ID  NUMBER(5) default 0,
  CORPS                VARCHAR2(50),
  TITLE                VARCHAR2(50),
  UNIT                 VARCHAR2(50),
  SQUADRON             VARCHAR2(50),
  PHONE                VARCHAR2(50),
  DIMS_ID              VARCHAR2(5) not null,
  ENTRY_DATE           DATE,
  LOCKED               NUMBER(1) default 0,
  MUST_CHANGE_PASSWORD NUMBER(1) default 0,
  FX_USER_ID           NUMBER,
  SUPERVISOR_ID        VARCHAR2(50),
  GRAPH_PREF           NUMBER default 0,
  XFER_SYSTEM_ID       NUMBER,
  XFER_DATE            DATE
)
;
comment on table TBICDS.APP_USER
  is 'Contains information related to a user of the system.';
comment on column TBICDS.APP_USER.EMAIL
  is 'N/A User Email Address';
comment on column TBICDS.APP_USER.UIDPWD
  is 'N/A User ID and Password';
comment on column TBICDS.APP_USER.RANK
  is 'N/A User Rank';
comment on column TBICDS.APP_USER.NAME
  is 'User First and Last Name';
comment on column TBICDS.APP_USER.PROVIDER_ID
  is 'Unique Provider ID of the user in the system (pk)';
comment on column TBICDS.APP_USER.MILITARY_SERVICE_ID
  is 'N/A Military Service ID';
comment on column TBICDS.APP_USER.CORPS
  is 'N/A Corps';
comment on column TBICDS.APP_USER.TITLE
  is 'N/A Job Title';
comment on column TBICDS.APP_USER.UNIT
  is 'N/A User Unit';
comment on column TBICDS.APP_USER.SQUADRON
  is 'N/A User Squadron';
comment on column TBICDS.APP_USER.PHONE
  is 'N/A User Contact Phone Number';
comment on column TBICDS.APP_USER.DIMS_ID
  is 'N/A DMIS/Base ID';
comment on column TBICDS.APP_USER.ENTRY_DATE
  is 'Record Entry Date';
comment on column TBICDS.APP_USER.LOCKED
  is 'N/A Flag Indicating Whether Or Not Account Is Locked';
comment on column TBICDS.APP_USER.MUST_CHANGE_PASSWORD
  is 'N/A Flag Indicating That The User Must Change Password On Next Login';
comment on column TBICDS.APP_USER.FX_USER_ID
  is 'N/A User ID Linked To The FX_USER_TABLE';
comment on column TBICDS.APP_USER.SUPERVISOR_ID
  is 'N/A Provider ID of the Intern''s Supervisor';
comment on column TBICDS.APP_USER.GRAPH_PREF
  is 'Users graphing preference 0: single graph, 1: multiple graphs';
comment on column TBICDS.APP_USER.XFER_SYSTEM_ID
  is 'ID of system if the record was transferred from an external system';
comment on column TBICDS.APP_USER.XFER_DATE
  is 'Date/time record was transferred from external system';
alter table TBICDS.APP_USER
  add constraint PK_SUAT_USER primary key (PROVIDER_ID, DIMS_ID);
create index TBICDS.DIMS_ID_1 on TBICDS.APP_USER (DIMS_ID);
create unique index TBICDS.PROVIDER_ID on TBICDS.APP_USER (PROVIDER_ID);

prompt
prompt Creating table CDE_MAP_TYPE
prompt ===========================
prompt
create table TBICDS.CDE_MAP_TYPE
(
  CDE_MAP_TYPE_ID NUMBER not null,
  CDE_MAP_TYPE    VARCHAR2(255)
)
;
comment on table TBICDS.CDE_MAP_TYPE
  is 'Contains CDE map types';
alter table TBICDS.CDE_MAP_TYPE
  add constraint CDE_MAP_TYPE_PK primary key (CDE_MAP_TYPE_ID);

prompt
prompt Creating table CDE_STAT
prompt =======================
prompt
create table TBICDS.CDE_STAT
(
  CDE_ID             VARCHAR2(30) not null,
  CDE_NAME           VARCHAR2(4000),
  VARIABLE_NAME      VARCHAR2(4000),
  DEFINITION         VARCHAR2(4000),
  QUESTION_TEXT      VARCHAR2(4000),
  PERMISSIBLE_VALUE  VARCHAR2(4000),
  DESCRIPTION        VARCHAR2(4000),
  DATA_TYPE          VARCHAR2(4000),
  INSTRUCTIONS       VARCHAR2(4000),
  REFERENCES         VARCHAR2(4000),
  POPULATION         VARCHAR2(4000),
  CLASSIFICATION     VARCHAR2(4000),
  VERSION_NUMBER     VARCHAR2(4000),
  VERSION_DATE       VARCHAR2(4000),
  ALIASES            VARCHAR2(4000),
  CRF_MODULE         VARCHAR2(4000),
  TM                 VARCHAR2(4000),
  SUB_DOMAIN         VARCHAR2(4000),
  DOMAIN             VARCHAR2(4000),
  PREVIOUS_TITLE     VARCHAR2(4000),
  VARIABLE_SIZE      VARCHAR2(4000),
  INPUT_RESTRICTIONS VARCHAR2(4000),
  MIN_VALUE          VARCHAR2(4000),
  MAX_VALUE          VARCHAR2(4000),
  MEASUREMENT_TYPE   VARCHAR2(4000),
  LOINC_ID           VARCHAR2(4000),
  SNOMED             VARCHAR2(4000),
  CADSR_ID           VARCHAR2(4000),
  CDISC_ID           VARCHAR2(4000),
  DATA_SOURCE        VARCHAR2(128)
)
;
comment on table TBICDS.CDE_STAT
  is 'FULL COMMON DATA ELEMENT LIST';
alter table TBICDS.CDE_STAT
  add constraint CDE_STAT_KEYPK primary key (CDE_ID);

prompt
prompt Creating table CDE_STAT_MAP
prompt ===========================
prompt
create table TBICDS.CDE_STAT_MAP
(
  CDE_ID          VARCHAR2(30),
  INTAKE_MID      NUMBER,
  INTAKE_TID      NUMBER,
  INTAKE_QID      NUMBER,
  INTAKE_RID      NUMBER,
  SCORE_SERIES    NUMBER,
  TABLE_NAME      VARCHAR2(255),
  FIELD_NAME      VARCHAR2(255),
  CDE_MAP_TYPE_ID NUMBER,
  MAP_DESCRIPTION VARCHAR2(1024)
)
;
comment on column TBICDS.CDE_STAT_MAP.CDE_ID
  is 'Unique TBI CDE Identification';
alter table TBICDS.CDE_STAT_MAP
  add constraint CDE_MAP_TYPE_KEYFK01 foreign key (CDE_ID)
  references TBICDS.CDE_STAT (CDE_ID);
alter table TBICDS.CDE_STAT_MAP
  add constraint CDE_MAP_TYPE_KEYFK02 foreign key (CDE_MAP_TYPE_ID)
  references TBICDS.CDE_MAP_TYPE (CDE_MAP_TYPE_ID);
create index TBICDS.CDE_STAT_MAP_NDX01 on TBICDS.CDE_STAT_MAP (CDE_ID);

prompt
prompt Creating table CPA
prompt ==================
prompt
create table TBICDS.CPA
(
  CPA_ID      NUMBER not null,
  CPA_TITLE   VARCHAR2(255),
  CPA_DESCR   VARCHAR2(1024),
  REGION_ID   NUMBER,
  SITE_ID     NUMBER,
  CPA_TYPE_ID NUMBER,
  SORT_ORDER  NUMBER,
  CPA_ABBR    VARCHAR2(25)
)
;
comment on table TBICDS.CPA
  is 'Contains information related to a clinical program area. Each MDWS site has it''s own list of clinical program areas. CPA_TYPE_ID identifies the type of program.';
comment on column TBICDS.CPA.CPA_ID
  is 'Clinical program area id (pk)';
comment on column TBICDS.CPA.CPA_TITLE
  is 'Clinical progam area title';
comment on column TBICDS.CPA.CPA_DESCR
  is 'Clinical program area description';
comment on column TBICDS.CPA.REGION_ID
  is 'Region ID (fk)';
comment on column TBICDS.CPA.SITE_ID
  is 'Site ID (fk)';
comment on column TBICDS.CPA.CPA_TYPE_ID
  is 'Type of clinical program area (fk)';
comment on column TBICDS.CPA.SORT_ORDER
  is 'Sort order for display';
comment on column TBICDS.CPA.CPA_ABBR
  is 'Abbrevation';
alter table TBICDS.CPA
  add constraint CPA_AREA_PK primary key (CPA_ID);

prompt
prompt Creating table CPA_PW_TYPE
prompt ==========================
prompt
create table TBICDS.CPA_PW_TYPE
(
  PW_TYPE_ID    NUMBER not null,
  PW_TYPE_TITLE VARCHAR2(255),
  PW_TYPE_DESCR VARCHAR2(1024)
)
;
comment on table TBICDS.CPA_PW_TYPE
  is 'Contains information related to the type of pathway. Pathway types include Inpatient and Outpatient';
comment on column TBICDS.CPA_PW_TYPE.PW_TYPE_ID
  is 'Pathway type id (pk)';
comment on column TBICDS.CPA_PW_TYPE.PW_TYPE_TITLE
  is 'Pathway type title';
comment on column TBICDS.CPA_PW_TYPE.PW_TYPE_DESCR
  is 'Pathway type description';
alter table TBICDS.CPA_PW_TYPE
  add constraint CPA_PW_TYPE_PK primary key (PW_TYPE_ID);

prompt
prompt Creating table UTL_REGION
prompt =========================
prompt
create table TBICDS.UTL_REGION
(
  REGION_ID      NUMBER not null,
  REGION_NAME    VARCHAR2(500),
  XFER_SYSTEM_ID NUMBER,
  XFER_DATE      DATE
)
;
comment on table TBICDS.UTL_REGION
  is 'Contains region information transferred from MDWS';
comment on column TBICDS.UTL_REGION.REGION_ID
  is 'Region ID (pk)';
comment on column TBICDS.UTL_REGION.REGION_NAME
  is 'Region name';
comment on column TBICDS.UTL_REGION.XFER_SYSTEM_ID
  is 'Transfer system ID (MDWS)';
comment on column TBICDS.UTL_REGION.XFER_DATE
  is 'Transfer date/time';
alter table TBICDS.UTL_REGION
  add constraint PKREGIONID primary key (REGION_ID);

prompt
prompt Creating table UTL_SITE
prompt =======================
prompt
create table TBICDS.UTL_SITE
(
  REGION_ID      NUMBER not null,
  SITE_ID        NUMBER not null,
  SITE_NAME      VARCHAR2(500),
  XFER_SYSTEM_ID NUMBER,
  XFER_DATE      DATE,
  SRV            VARCHAR2(100),
  PORT           VARCHAR2(100)
)
;
comment on table TBICDS.UTL_SITE
  is 'Contains site information transferred from MDWS';
comment on column TBICDS.UTL_SITE.REGION_ID
  is 'Region ID (pk)';
comment on column TBICDS.UTL_SITE.SITE_ID
  is 'Site ID (pk)';
comment on column TBICDS.UTL_SITE.SITE_NAME
  is 'Site Name';
comment on column TBICDS.UTL_SITE.XFER_SYSTEM_ID
  is 'Transfer system ID (MDWS)';
comment on column TBICDS.UTL_SITE.XFER_DATE
  is 'Transfer date/time';
comment on column TBICDS.UTL_SITE.SRV
  is 'SRV param passed from CPRS (IP address)';
comment on column TBICDS.UTL_SITE.PORT
  is 'PORT param passed from CPRS';
alter table TBICDS.UTL_SITE
  add constraint PKSITEID primary key (REGION_ID, SITE_ID);
alter table TBICDS.UTL_SITE
  add constraint SITE_FK1 foreign key (REGION_ID)
  references TBICDS.UTL_REGION (REGION_ID);

prompt
prompt Creating table CPA_PW
prompt =====================
prompt
create table TBICDS.CPA_PW
(
  PW_ID      NUMBER not null,
  PW_TITLE   VARCHAR2(255),
  PW_DESCR   VARCHAR2(1024),
  PW_TYPE_ID NUMBER,
  CPA_ID     NUMBER,
  REGION_ID  NUMBER,
  SITE_ID    NUMBER
)
;
comment on table TBICDS.CPA_PW
  is 'Contains information related to a pathway schedule template. Each clinical program area has it''s own list of pathway templates.';
comment on column TBICDS.CPA_PW.PW_ID
  is 'Pathway ID (pk)';
comment on column TBICDS.CPA_PW.PW_TITLE
  is 'Title of the pathway';
comment on column TBICDS.CPA_PW.PW_DESCR
  is 'Description of the pathway';
comment on column TBICDS.CPA_PW.PW_TYPE_ID
  is 'Type of pathway: inpatient, outpatient, adhoc etc... (fk)';
comment on column TBICDS.CPA_PW.CPA_ID
  is 'Clinical program area ID (fk)';
comment on column TBICDS.CPA_PW.REGION_ID
  is 'Region ID (fk)';
comment on column TBICDS.CPA_PW.SITE_ID
  is 'Site ID (fk)';
alter table TBICDS.CPA_PW
  add constraint CPA_PW_PATHWAY_PK primary key (PW_ID);
alter table TBICDS.CPA_PW
  add constraint PW_FK1 foreign key (CPA_ID)
  references TBICDS.CPA (CPA_ID);
alter table TBICDS.CPA_PW
  add constraint PW_FK2 foreign key (PW_TYPE_ID)
  references TBICDS.CPA_PW_TYPE (PW_TYPE_ID);
alter table TBICDS.CPA_PW
  add constraint PW_FK3 foreign key (REGION_ID, SITE_ID)
  references TBICDS.UTL_SITE (REGION_ID, SITE_ID);

prompt
prompt Creating table CPA_PW_EVENT
prompt ===========================
prompt
create table TBICDS.CPA_PW_EVENT
(
  PW_ID            NUMBER not null,
  PW_EVENT_ID      NUMBER not null,
  EVENT_TITLE      VARCHAR2(255) not null,
  EVENT_DESCR      VARCHAR2(1024),
  SORT_ORDER       NUMBER,
  EVENT_FREQUENCY  NUMBER not null,
  REGION_ID        NUMBER not null,
  SITE_ID          NUMBER not null,
  CPA_ID           NUMBER not null,
  PW_EVENT_TYPE_ID NUMBER not null
)
;
comment on table TBICDS.CPA_PW_EVENT
  is 'Contains information related to a pathway event. Each pathway template has one or more events defined. For exmple: 30 day, 60 Day, 90 Day etc...';
comment on column TBICDS.CPA_PW_EVENT.PW_ID
  is 'Pathway ID (pk)';
comment on column TBICDS.CPA_PW_EVENT.PW_EVENT_ID
  is 'Pathway event ID (pk)';
comment on column TBICDS.CPA_PW_EVENT.EVENT_TITLE
  is 'Pathway event title';
comment on column TBICDS.CPA_PW_EVENT.EVENT_DESCR
  is 'Pathway event description';
comment on column TBICDS.CPA_PW_EVENT.SORT_ORDER
  is 'Pathway event sort order';
comment on column TBICDS.CPA_PW_EVENT.EVENT_FREQUENCY
  is 'Pathway event frequency';
comment on column TBICDS.CPA_PW_EVENT.REGION_ID
  is 'Region ID (fk)';
comment on column TBICDS.CPA_PW_EVENT.SITE_ID
  is 'Site ID (fk)';
comment on column TBICDS.CPA_PW_EVENT.CPA_ID
  is 'Clinical program area ID (fk)';
comment on column TBICDS.CPA_PW_EVENT.PW_EVENT_TYPE_ID
  is 'Event type: 1=scheduled, 2=out of cycle (fk)';
alter table TBICDS.CPA_PW_EVENT
  add constraint CPA_PW_EVENT_PK primary key (PW_ID, PW_EVENT_ID);
alter table TBICDS.CPA_PW_EVENT
  add constraint PW_EVENT_FK1 foreign key (PW_ID)
  references TBICDS.CPA_PW (PW_ID);

prompt
prompt Creating table INTAKE_MODULE
prompt ============================
prompt
create table TBICDS.INTAKE_MODULE
(
  MID                  NUMBER(5) default 0 not null,
  MODULE               VARCHAR2(124) not null,
  ACTIVE               NUMBER(5) not null,
  DESCRIPTION          VARCHAR2(4000),
  SORT_ORDER           NUMBER(6) default 0 not null,
  RENDER_GRAPH         NUMBER(2) default 0,
  MODULE_ALT_LANG      VARCHAR2(80),
  DESCRIPTION_ALT_LANG VARCHAR2(4000),
  ACRONYM              VARCHAR2(48),
  SCORE_LOGIC          CLOB,
  CLIENTSIDE_CODE      CLOB,
  MODULE_FOR           NUMBER default 3,
  IDENTIFIER           VARCHAR2(48),
  MODULE_TYPE          NUMBER default 0,
  EDITABLE             NUMBER default 0
)
;
comment on table TBICDS.INTAKE_MODULE
  is 'Contains information related to an Instrument';
comment on column TBICDS.INTAKE_MODULE.MID
  is 'Module ID (pk)';
comment on column TBICDS.INTAKE_MODULE.MODULE
  is 'Module title';
comment on column TBICDS.INTAKE_MODULE.ACTIVE
  is 'Is this module active';
comment on column TBICDS.INTAKE_MODULE.DESCRIPTION
  is 'Module description';
comment on column TBICDS.INTAKE_MODULE.SORT_ORDER
  is 'Sort order for display';
comment on column TBICDS.INTAKE_MODULE.RENDER_GRAPH
  is 'Is graph rendered: 0=do not render this module scores in the graphic hub';
comment on column TBICDS.INTAKE_MODULE.MODULE_ALT_LANG
  is 'Module name alternate language';
comment on column TBICDS.INTAKE_MODULE.DESCRIPTION_ALT_LANG
  is 'Module description alternate language';
comment on column TBICDS.INTAKE_MODULE.ACRONYM
  is 'Module acronym';
comment on column TBICDS.INTAKE_MODULE.SCORE_LOGIC
  is 'Module score logic';
comment on column TBICDS.INTAKE_MODULE.CLIENTSIDE_CODE
  is 'Module ClientSide Scripts';
comment on column TBICDS.INTAKE_MODULE.MODULE_FOR
  is 'Instrument for 1=provider, 2=patient, 3=both';
comment on column TBICDS.INTAKE_MODULE.IDENTIFIER
  is 'Identifier';
comment on column TBICDS.INTAKE_MODULE.MODULE_TYPE
  is '0 = Instrument, 1 = Internal/System Module';
comment on column TBICDS.INTAKE_MODULE.EDITABLE
  is '0 = Not editable (questionnaire must be completed in full), 1 = Editable (questionnaire can be submitted incomplete)';
alter table TBICDS.INTAKE_MODULE
  add constraint PRIMARYKEY00022 primary key (MID);

prompt
prompt Creating table CPA_PW_EVENT_MODULE
prompt ==================================
prompt
create table TBICDS.CPA_PW_EVENT_MODULE
(
  PW_ID       NUMBER not null,
  PW_EVENT_ID NUMBER not null,
  MID         NUMBER not null,
  MODULE_FOR  NUMBER,
  SORT_ORDER  NUMBER,
  CPA_ID      NUMBER,
  REGION_ID   NUMBER,
  SITE_ID     NUMBER
)
;
comment on table TBICDS.CPA_PW_EVENT_MODULE
  is 'Contains information related to a pathway event instrument. Each pathway event can have 1 or more instruments associated with it. This is the list of instruments that should be completed for the pathway event.';
comment on column TBICDS.CPA_PW_EVENT_MODULE.PW_ID
  is 'Pathway ID (pk)';
comment on column TBICDS.CPA_PW_EVENT_MODULE.PW_EVENT_ID
  is 'Pathway event ID (pk)';
comment on column TBICDS.CPA_PW_EVENT_MODULE.MID
  is 'Module id of the instrument (pk)';
comment on column TBICDS.CPA_PW_EVENT_MODULE.MODULE_FOR
  is 'Instrument for 1=provider, 2=patient, 3=both';
comment on column TBICDS.CPA_PW_EVENT_MODULE.SORT_ORDER
  is 'Sort order for display';
comment on column TBICDS.CPA_PW_EVENT_MODULE.CPA_ID
  is 'Clinical program area id (fk)';
comment on column TBICDS.CPA_PW_EVENT_MODULE.REGION_ID
  is 'Region id (fk)';
comment on column TBICDS.CPA_PW_EVENT_MODULE.SITE_ID
  is 'Site id (fk)';
alter table TBICDS.CPA_PW_EVENT_MODULE
  add constraint CPA_PW_EVENT_MID_PK primary key (PW_ID, PW_EVENT_ID, MID);
alter table TBICDS.CPA_PW_EVENT_MODULE
  add constraint CPA_PW_EVENT_MID_FK1 foreign key (PW_ID, PW_EVENT_ID)
  references TBICDS.CPA_PW_EVENT (PW_ID, PW_EVENT_ID);
alter table TBICDS.CPA_PW_EVENT_MODULE
  add constraint CPA_PW_EVENT_MID_FK2 foreign key (MID)
  references TBICDS.INTAKE_MODULE (MID);

prompt
prompt Creating table CPA_PW_EVENT_TYPE
prompt ================================
prompt
create table TBICDS.CPA_PW_EVENT_TYPE
(
  PW_EVENT_TYPE_ID    NUMBER not null,
  PW_EVENT_TYPE_TITLE VARCHAR2(100)
)
;
comment on table TBICDS.CPA_PW_EVENT_TYPE
  is 'Contains information related to the type of pathway event. For example: Scheduled or Out of cycle.';
comment on column TBICDS.CPA_PW_EVENT_TYPE.PW_EVENT_TYPE_ID
  is 'Event type ID (pk)';
comment on column TBICDS.CPA_PW_EVENT_TYPE.PW_EVENT_TYPE_TITLE
  is 'Event type title';
alter table TBICDS.CPA_PW_EVENT_TYPE
  add constraint PKEVENTTYPEID primary key (PW_EVENT_TYPE_ID);

prompt
prompt Creating table CPA_TYPE
prompt =======================
prompt
create table TBICDS.CPA_TYPE
(
  CPA_TYPE_ID    NUMBER not null,
  CPA_TYPE_TITLE VARCHAR2(255),
  CPA_TYPE_DESCR VARCHAR2(1000),
  SORT_ORDER     NUMBER
)
;
comment on table TBICDS.CPA_TYPE
  is 'Contains information related to the type of clinical program area. Types include:  PRC, EC, PT etc...';
comment on column TBICDS.CPA_TYPE.CPA_TYPE_ID
  is 'Clinical program area type id (pk)';
comment on column TBICDS.CPA_TYPE.CPA_TYPE_TITLE
  is 'Clinical program area type title';
comment on column TBICDS.CPA_TYPE.CPA_TYPE_DESCR
  is 'Clinical program area type description';
comment on column TBICDS.CPA_TYPE.SORT_ORDER
  is 'Sort order for dispaly';
alter table TBICDS.CPA_TYPE
  add constraint PKCPATYPEID primary key (CPA_TYPE_ID);

prompt
prompt Creating table DATA_INTAKE
prompt ==========================
prompt
create table TBICDS.DATA_INTAKE
(
  PATIENT_ID          VARCHAR2(60) not null,
  INTAKE_ID           NUMBER(5) not null,
  MID                 NUMBER(5) default 0 not null,
  INTAKE_TYPE         NUMBER(5) default 0,
  SCORE               NUMBER(11) default 0,
  READ_ONLY           NUMBER(3) default 0 not null,
  COMPLETE            NUMBER(3) default 0,
  ALTERNATE_LANGUAGE  NUMBER default 0,
  REVIEW_ENCOUNTER_ID VARCHAR2(50),
  REVIEW_PROVIDER_ID  VARCHAR2(50),
  REVIEW_DATE         DATE,
  STAT_MODALITY_ID    NUMBER,
  COMPLETE_DATE       DATE,
  START_DATE          DATE
)
;
comment on table TBICDS.DATA_INTAKE
  is 'Contains information related to instruments taken by a patient';
comment on column TBICDS.DATA_INTAKE.PATIENT_ID
  is 'Patient ID (pk)';
comment on column TBICDS.DATA_INTAKE.INTAKE_ID
  is 'Intake ID (pk)';
comment on column TBICDS.DATA_INTAKE.MID
  is 'Module/instrument ID (fk)';
comment on column TBICDS.DATA_INTAKE.INTAKE_TYPE
  is 'Type of intake';
comment on column TBICDS.DATA_INTAKE.SCORE
  is 'Score';
comment on column TBICDS.DATA_INTAKE.READ_ONLY
  is 'Is this instance read only';
comment on column TBICDS.DATA_INTAKE.COMPLETE
  is 'Instrument complete';
comment on column TBICDS.DATA_INTAKE.ALTERNATE_LANGUAGE
  is 'Alternate language 0=english, 1 = spanish';
comment on column TBICDS.DATA_INTAKE.REVIEW_ENCOUNTER_ID
  is 'Encounter id that the intake was reviewed on';
comment on column TBICDS.DATA_INTAKE.REVIEW_PROVIDER_ID
  is 'Provider ID that reviewed the intake';
comment on column TBICDS.DATA_INTAKE.REVIEW_DATE
  is 'Date the intake was reviewed';
comment on column TBICDS.DATA_INTAKE.STAT_MODALITY_ID
  is 'N/A';
comment on column TBICDS.DATA_INTAKE.COMPLETE_DATE
  is 'Date the module was completed';
comment on column TBICDS.DATA_INTAKE.START_DATE
  is 'Date the module was started';
alter table TBICDS.DATA_INTAKE
  add constraint PK_DATA_INTAKE primary key (PATIENT_ID, INTAKE_ID, MID);

prompt
prompt Creating table DATA_INTAKE_RESPONSES
prompt ====================================
prompt
create table TBICDS.DATA_INTAKE_RESPONSES
(
  PATIENT_ID        VARCHAR2(60) not null,
  INTAKE_ID         NUMBER(5) not null,
  RID               NUMBER(5) not null,
  MID               NUMBER(5) not null,
  TID               NUMBER(5) not null,
  QID               NUMBER(5) not null,
  RESPONSE_TYPE     NUMBER(5) default 0,
  RESPONSE_VALUE    VARCHAR2(4000),
  SCORE_VALUE       NUMBER default 0,
  RESPONSE_DATETIME DATE,
  RESPONSE_TIME     NUMBER,
  INTAKE_GROUP_ID   NUMBER,
  IDENTIFIER        VARCHAR2(24)
)
;
comment on table TBICDS.DATA_INTAKE_RESPONSES
  is 'Contains the responses/answers of an instrument during one patient session.';
comment on column TBICDS.DATA_INTAKE_RESPONSES.PATIENT_ID
  is 'Patient ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES.INTAKE_ID
  is 'Intake ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES.RID
  is 'Response ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES.MID
  is 'Module ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES.TID
  is 'Topic ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES.QID
  is 'Question ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES.RESPONSE_TYPE
  is 'Type of response';
comment on column TBICDS.DATA_INTAKE_RESPONSES.RESPONSE_VALUE
  is 'Value of response';
comment on column TBICDS.DATA_INTAKE_RESPONSES.SCORE_VALUE
  is 'Score value of response';
comment on column TBICDS.DATA_INTAKE_RESPONSES.RESPONSE_DATETIME
  is 'Date/Time response was entered';
comment on column TBICDS.DATA_INTAKE_RESPONSES.RESPONSE_TIME
  is 'N/A';
comment on column TBICDS.DATA_INTAKE_RESPONSES.INTAKE_GROUP_ID
  is 'N/A Group ID';
comment on column TBICDS.DATA_INTAKE_RESPONSES.IDENTIFIER
  is 'Response Identifier';
alter table TBICDS.DATA_INTAKE_RESPONSES
  add constraint PK_DATA_INTAKE_RESP primary key (PATIENT_ID, INTAKE_ID, MID, TID, QID, RID);
alter table TBICDS.DATA_INTAKE_RESPONSES
  add constraint FK_CASCADE_DI foreign key (PATIENT_ID, INTAKE_ID, MID)
  references TBICDS.DATA_INTAKE (PATIENT_ID, INTAKE_ID, MID) on delete cascade;
create index TBICDS.DATA_INTAKE_RESPONSES_NDX01 on TBICDS.DATA_INTAKE_RESPONSES (PATIENT_ID);
create index TBICDS.DATA_INTAKE_RESPONSES_NDX02 on TBICDS.DATA_INTAKE_RESPONSES (INTAKE_ID);
create index TBICDS.DATA_INTAKE_RESPONSES_NDX03 on TBICDS.DATA_INTAKE_RESPONSES (MID);
create index TBICDS.DATA_INTAKE_RESPONSES_NDX04 on TBICDS.DATA_INTAKE_RESPONSES (TID);
create index TBICDS.DATA_INTAKE_RESPONSES_NDX05 on TBICDS.DATA_INTAKE_RESPONSES (QID);
create index TBICDS.DATA_INTAKE_RESPONSES_NDX06 on TBICDS.DATA_INTAKE_RESPONSES (RID);

prompt
prompt Creating table DATA_INTAKE_RESPONSES_AUDIT
prompt ==========================================
prompt
create table TBICDS.DATA_INTAKE_RESPONSES_AUDIT
(
  PATIENT_ID        VARCHAR2(60) not null,
  INTAKE_ID         NUMBER(5) not null,
  RID               NUMBER(5) not null,
  COMPLETE_DATE     DATE,
  MID               NUMBER(5) not null,
  TID               NUMBER(5) not null,
  QID               NUMBER(5) not null,
  RESPONSE_TYPE     NUMBER(5) default 0,
  RESPONSE_VALUE    VARCHAR2(4000),
  SCORE_VALUE       NUMBER default 0,
  RESPONSE_DATETIME DATE not null,
  RESPONSE_TIME     NUMBER,
  INTAKE_GROUP_ID   NUMBER,
  IDENTIFIER        VARCHAR2(24)
)
;
comment on table TBICDS.DATA_INTAKE_RESPONSES_AUDIT
  is 'Contains the responses/answers of an instrument during one patient session.';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.PATIENT_ID
  is 'Patient ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.INTAKE_ID
  is 'Intake ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.RID
  is 'Response ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.COMPLETE_DATE
  is 'Date the module was completed';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.MID
  is 'Module ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.TID
  is 'Topic ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.QID
  is 'Question ID (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.RESPONSE_TYPE
  is 'Type of response';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.RESPONSE_VALUE
  is 'Value of response';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.SCORE_VALUE
  is 'Score value of response';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.RESPONSE_DATETIME
  is 'Date/Time response was entered (pk)';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.RESPONSE_TIME
  is 'N/A';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.INTAKE_GROUP_ID
  is 'N/A Group ID';
comment on column TBICDS.DATA_INTAKE_RESPONSES_AUDIT.IDENTIFIER
  is 'Response Identifier';
alter table TBICDS.DATA_INTAKE_RESPONSES_AUDIT
  add constraint DATA_INTAKE_RESPONSES_AUDIT_PK primary key (PATIENT_ID, INTAKE_ID, MID, TID, QID, RID, RESPONSE_DATETIME);
alter table TBICDS.DATA_INTAKE_RESPONSES_AUDIT
  add constraint FK_CASCADE_AUDIT_DI foreign key (PATIENT_ID, INTAKE_ID, MID)
  references TBICDS.DATA_INTAKE (PATIENT_ID, INTAKE_ID, MID) on delete cascade;

prompt
prompt Creating table DATA_INTAKE_REVIEW
prompt =================================
prompt
create table TBICDS.DATA_INTAKE_REVIEW
(
  PATIENT_ID   VARCHAR2(60) not null,
  ENCOUNTER_ID VARCHAR2(60) not null,
  INTAKE_ID    NUMBER not null,
  REVIEW_DATE  DATE,
  REVIEWED_BY  NUMBER
)
;
comment on table TBICDS.DATA_INTAKE_REVIEW
  is 'Contains information related to a provider review of an instrument.';
comment on column TBICDS.DATA_INTAKE_REVIEW.PATIENT_ID
  is 'Patient ID (pk)';
comment on column TBICDS.DATA_INTAKE_REVIEW.ENCOUNTER_ID
  is 'Encounter ID (pk)';
comment on column TBICDS.DATA_INTAKE_REVIEW.INTAKE_ID
  is 'Intake ID (pk)';
comment on column TBICDS.DATA_INTAKE_REVIEW.REVIEW_DATE
  is 'Date/Time reviewed';
comment on column TBICDS.DATA_INTAKE_REVIEW.REVIEWED_BY
  is 'User ID who reviewed the intake (fk)';
alter table TBICDS.DATA_INTAKE_REVIEW
  add constraint DATA_INTAKE_REVIEW_PK primary key (PATIENT_ID, ENCOUNTER_ID, INTAKE_ID);

prompt
prompt Creating table DATA_INTAKE_SCORE
prompt ================================
prompt
create table TBICDS.DATA_INTAKE_SCORE
(
  PATIENT_ID     VARCHAR2(60) not null,
  MID            NUMBER(5) default 0 not null,
  INTAKE_ID      NUMBER(5) default 0 not null,
  SERIES         NUMBER default 1 not null,
  SCORE          NUMBER default 0,
  INTERPRETATION VARCHAR2(256) default 0,
  DESCRIPTION    VARCHAR2(256),
  SEVERITY       NUMBER(5) default 0
)
;
comment on table TBICDS.DATA_INTAKE_SCORE
  is 'Contains the scores triggered by an instrument during one session.';
comment on column TBICDS.DATA_INTAKE_SCORE.PATIENT_ID
  is 'Patient ID (pk)';
comment on column TBICDS.DATA_INTAKE_SCORE.MID
  is 'Module ID (pk)';
comment on column TBICDS.DATA_INTAKE_SCORE.INTAKE_ID
  is 'Intake ID (pk)';
comment on column TBICDS.DATA_INTAKE_SCORE.SERIES
  is 'Series sequential from 1 to n where 1 is the total score followed by sub-scores';
comment on column TBICDS.DATA_INTAKE_SCORE.SCORE
  is 'Score';
comment on column TBICDS.DATA_INTAKE_SCORE.INTERPRETATION
  is 'Interpretation ';
comment on column TBICDS.DATA_INTAKE_SCORE.DESCRIPTION
  is 'Description';
comment on column TBICDS.DATA_INTAKE_SCORE.SEVERITY
  is 'Severity: 0=unk, 1=mild, 2=moderate, 3=severe';
alter table TBICDS.DATA_INTAKE_SCORE
  add constraint PK_INTAKE_SCORE primary key (PATIENT_ID, MID, INTAKE_ID, SERIES);
alter table TBICDS.DATA_INTAKE_SCORE
  add constraint FK_CASCADE_SCORE_DI foreign key (PATIENT_ID, INTAKE_ID, MID)
  references TBICDS.DATA_INTAKE (PATIENT_ID, INTAKE_ID, MID) on delete cascade;

prompt
prompt Creating table DATA_INTAKE_SCORE_AUDIT
prompt ======================================
prompt
create table TBICDS.DATA_INTAKE_SCORE_AUDIT
(
  PATIENT_ID     VARCHAR2(60) not null,
  MID            NUMBER(5) default 0 not null,
  INTAKE_ID      NUMBER(5) default 0 not null,
  COMPLETE_DATE  DATE,
  SERIES         NUMBER default 1 not null,
  SCORE          NUMBER default 0,
  INTERPRETATION VARCHAR2(256) default 0,
  DESCRIPTION    VARCHAR2(256),
  SEVERITY       NUMBER(5) default 0,
  SCORE_DATETIME DATE default sysdate not null
)
;
comment on table TBICDS.DATA_INTAKE_SCORE_AUDIT
  is 'Contains the scores triggered by an instrument during one session.';
comment on column TBICDS.DATA_INTAKE_SCORE_AUDIT.PATIENT_ID
  is 'Patient ID (pk)';
comment on column TBICDS.DATA_INTAKE_SCORE_AUDIT.MID
  is 'Module ID (pk)';
comment on column TBICDS.DATA_INTAKE_SCORE_AUDIT.INTAKE_ID
  is 'Intake ID (pk)';
comment on column TBICDS.DATA_INTAKE_SCORE_AUDIT.COMPLETE_DATE
  is 'Date the module was completed';
comment on column TBICDS.DATA_INTAKE_SCORE_AUDIT.SERIES
  is 'Series sequential from 1 to n where 1 is the total score followed by sub-scores';
comment on column TBICDS.DATA_INTAKE_SCORE_AUDIT.SCORE
  is 'Score';
comment on column TBICDS.DATA_INTAKE_SCORE_AUDIT.INTERPRETATION
  is 'Interpretation ';
comment on column TBICDS.DATA_INTAKE_SCORE_AUDIT.DESCRIPTION
  is 'Description';
comment on column TBICDS.DATA_INTAKE_SCORE_AUDIT.SEVERITY
  is 'Severity: 0=unk, 1=mild, 2=moderate, 3=severe';
comment on column TBICDS.DATA_INTAKE_SCORE_AUDIT.SCORE_DATETIME
  is 'Datetime when the record was added
';
alter table TBICDS.DATA_INTAKE_SCORE_AUDIT
  add constraint FK_CASCADE_SAUDIT_DI foreign key (PATIENT_ID, INTAKE_ID, MID)
  references TBICDS.DATA_INTAKE (PATIENT_ID, INTAKE_ID, MID) on delete cascade;

prompt
prompt Creating table DEV_CALENDAR
prompt ===========================
prompt
create table TBICDS.DEV_CALENDAR
(
  CAL_EVENT_ID NUMBER,
  CALENDAR_ID  NUMBER not null,
  END_DATE     DATE,
  EVENT_ID     NUMBER,
  IS_ALL_DAY   NUMBER(1) default 0,
  LOCATION     VARCHAR2(255),
  NOTES        VARCHAR2(4000),
  REMINDER     NUMBER,
  START_DATE   DATE,
  TITLE        VARCHAR2(255) not null,
  URL          VARCHAR2(255),
  PATIENT_ID   VARCHAR2(64),
  PROVIDER_ID  VARCHAR2(64)
)
;

prompt
prompt Creating table DEV_STAT_CALENDAR
prompt ================================
prompt
create table TBICDS.DEV_STAT_CALENDAR
(
  CALENDAR_ID    NUMBER,
  CALENDAR_TITLE VARCHAR2(255),
  ACTIVE         NUMBER default 1
)
;

prompt
prompt Creating table FX_USER
prompt ======================
prompt
create table TBICDS.FX_USER
(
  FX_USER_ID            NUMBER not null,
  USER_NAME             VARCHAR2(500),
  IS_LOCKED             NUMBER,
  IS_INACTIVE           NUMBER,
  DATE_CREATED          DATE,
  DATE_MODIFIED         DATE,
  UPDATED_BY            NUMBER,
  DATE_LAST_LOGIN       DATE,
  SESSION_TIMEOUT       NUMBER,
  LOGIN_ATTEMPTS        NUMBER,
  PASSWORD              VARCHAR2(1500),
  LAST_UPDATED          DATE,
  LAST_UPDATED_BY       NUMBER,
  IV                    VARCHAR2(255),
  IV_PRE                VARCHAR2(255),
  PREV_PWD1             VARCHAR2(1500),
  PREV_PWD2             VARCHAR2(1500),
  PREV_PWD3             VARCHAR2(1500),
  PREV_PWD4             VARCHAR2(1500),
  PREV_PWD5             VARCHAR2(1500),
  PREV_PWD6             VARCHAR2(1500),
  PREV_PWD7             VARCHAR2(1500),
  PREV_PWD8             VARCHAR2(1500),
  PREV_PWD9             VARCHAR2(1500),
  PREV_PWD10            VARCHAR2(1500),
  LAST_FLOGIN_DATE      DATE,
  LAST_FLOGIN_IP        VARCHAR2(25),
  LAST_LOGIN_IP         VARCHAR2(25),
  FLOGIN_ATTEMPTS       NUMBER,
  DUZ                   VARCHAR2(500),
  REGION_ID             NUMBER,
  SITE_ID               NUMBER,
  GREETING              VARCHAR2(4000),
  XFER_SYSTEM_ID        NUMBER,
  XFER_DATE             DATE,
  DEFAULT_CPA_ID        NUMBER,
  RESET_PASSWORD        NUMBER,
  DATE_PASSWORD_CHANGED DATE
)
;
comment on table TBICDS.FX_USER
  is 'Contains information related to a user of the system.';
comment on column TBICDS.FX_USER.FX_USER_ID
  is 'Unique User ID links to the app_user table (pk)';
comment on column TBICDS.FX_USER.USER_NAME
  is 'N/A User Name - Encrypted';
comment on column TBICDS.FX_USER.IS_LOCKED
  is 'N/A Flag Indicating Whether Account Is Locked';
comment on column TBICDS.FX_USER.IS_INACTIVE
  is 'N/A Flag Indicating Whether Account Is Inactive';
comment on column TBICDS.FX_USER.DATE_CREATED
  is 'N/A Account Creation Date';
comment on column TBICDS.FX_USER.DATE_MODIFIED
  is 'N/A Last Modified Date';
comment on column TBICDS.FX_USER.UPDATED_BY
  is 'N/A FX User ID Of Last User To Modify Record ';
comment on column TBICDS.FX_USER.DATE_LAST_LOGIN
  is 'N/A Date The Last Time The User Logged In';
comment on column TBICDS.FX_USER.SESSION_TIMEOUT
  is 'Session Timeout IN Minutes';
comment on column TBICDS.FX_USER.LOGIN_ATTEMPTS
  is 'N/A Number of Unsuccessful Login Attempts';
comment on column TBICDS.FX_USER.PASSWORD
  is 'N/A Password - Encrypted';
comment on column TBICDS.FX_USER.LAST_UPDATED
  is 'N/A Date Last Updated';
comment on column TBICDS.FX_USER.LAST_UPDATED_BY
  is 'N/A FX User ID Of Last User To Update';
comment on column TBICDS.FX_USER.IV
  is 'N/A ';
comment on column TBICDS.FX_USER.IV_PRE
  is 'N/A ';
comment on column TBICDS.FX_USER.PREV_PWD1
  is 'N/A Previous Password 1 of Last 10 Passwords';
comment on column TBICDS.FX_USER.PREV_PWD2
  is 'N/A Previous Password 2 of Last 10 Passwords';
comment on column TBICDS.FX_USER.PREV_PWD3
  is 'N/A Previous Password 3 of Last 10 Passwords';
comment on column TBICDS.FX_USER.PREV_PWD4
  is 'N/A Previous Password 4 of Last 10 Passwords';
comment on column TBICDS.FX_USER.PREV_PWD5
  is 'N/A Previous Password 5 of Last 10 Passwords';
comment on column TBICDS.FX_USER.PREV_PWD6
  is 'N/A Previous Password 5 of Last 10 Passwords';
comment on column TBICDS.FX_USER.PREV_PWD7
  is 'N/A Previous Password 6 of Last 10 Passwords';
comment on column TBICDS.FX_USER.PREV_PWD8
  is 'N/A Previous Password 8 of Last 10 Passwords';
comment on column TBICDS.FX_USER.PREV_PWD9
  is 'N/A Previous Password 9 of Last 10 Passwords';
comment on column TBICDS.FX_USER.PREV_PWD10
  is 'N/A Previous Password 10 of Last 10 Passwords';
comment on column TBICDS.FX_USER.LAST_FLOGIN_DATE
  is 'N/A Last Failed Login Date';
comment on column TBICDS.FX_USER.LAST_FLOGIN_IP
  is 'N/A Last Failed Login IP Address';
comment on column TBICDS.FX_USER.LAST_LOGIN_IP
  is 'N/A Last Successful Login IP Address';
comment on column TBICDS.FX_USER.FLOGIN_ATTEMPTS
  is 'N/A Number Of Failed Login Attempts';
comment on column TBICDS.FX_USER.DUZ
  is 'VA DUZ id of the user';
comment on column TBICDS.FX_USER.REGION_ID
  is 'VA region id of the user';
comment on column TBICDS.FX_USER.SITE_ID
  is 'VA site id of the user';
comment on column TBICDS.FX_USER.GREETING
  is 'VA greeting';
comment on column TBICDS.FX_USER.XFER_SYSTEM_ID
  is 'ID of system if the record was transferred';
comment on column TBICDS.FX_USER.XFER_DATE
  is 'Date record was transferred from external system';
comment on column TBICDS.FX_USER.DEFAULT_CPA_ID
  is 'N/A default program area for this user';
comment on column TBICDS.FX_USER.RESET_PASSWORD
  is 'N/A Flag Indicating Whether User Needs To Reset Password';
comment on column TBICDS.FX_USER.DATE_PASSWORD_CHANGED
  is 'N/A Date Of Last Password Change';
alter table TBICDS.FX_USER
  add constraint FX_USER_KEY_PK primary key (FX_USER_ID);

prompt
prompt Creating table EXP_STATISTICAL_RPT
prompt ==================================
prompt
create table TBICDS.EXP_STATISTICAL_RPT
(
  REQUEST_ID     NUMBER not null,
  FX_USER_ID     NUMBER not null,
  REPORT_NAME    VARCHAR2(255),
  FILTERS        VARCHAR2(1024),
  DATA_INCLUDED  VARCHAR2(1024),
  STATUS         NUMBER default 0 not null,
  START_DATE     DATE,
  END_DATE       DATE,
  FILE_DATA      CLOB,
  STATUS_COMMENT VARCHAR2(4000)
)
;
comment on column TBICDS.EXP_STATISTICAL_RPT.REQUEST_ID
  is 'Sequential id for the request export statistical report';
comment on column TBICDS.EXP_STATISTICAL_RPT.FILTERS
  is 'Comma separated filters for the file';
comment on column TBICDS.EXP_STATISTICAL_RPT.DATA_INCLUDED
  is 'Comma separated data fields selected by user to be included in the file';
comment on column TBICDS.EXP_STATISTICAL_RPT.STATUS
  is '0 = New (yet not defined), 1 = In Process, 2 = Ready for Download, 3 = Canceled';
comment on column TBICDS.EXP_STATISTICAL_RPT.FILE_DATA
  is 'Result for current request';
alter table TBICDS.EXP_STATISTICAL_RPT
  add constraint EXP_STATISTICAL_RPT_PK primary key (REQUEST_ID);
alter table TBICDS.EXP_STATISTICAL_RPT
  add constraint EXP_STATISTICAL_RPT_FK foreign key (FX_USER_ID)
  references TBICDS.FX_USER (FX_USER_ID) on delete cascade;

prompt
prompt Creating table EXP_STATISTICAL_RPT_AUDIT
prompt ========================================
prompt
create table TBICDS.EXP_STATISTICAL_RPT_AUDIT
(
  REQUEST_ID            NUMBER,
  FX_USER_ID            NUMBER,
  REQUEST_DOWNLOAD_DATE DATE
)
;
comment on column TBICDS.EXP_STATISTICAL_RPT_AUDIT.REQUEST_ID
  is 'File ID requested (ID of the export request with the data in the FILE_DATA field).';
comment on column TBICDS.EXP_STATISTICAL_RPT_AUDIT.FX_USER_ID
  is 'FX_USER_ID of the person requesting the download.';
comment on column TBICDS.EXP_STATISTICAL_RPT_AUDIT.REQUEST_DOWNLOAD_DATE
  is 'Date when the request for download was issue.';
alter table TBICDS.EXP_STATISTICAL_RPT_AUDIT
  add constraint FK_STAT_AUDIT_REQUEST_ID foreign key (REQUEST_ID)
  references TBICDS.EXP_STATISTICAL_RPT (REQUEST_ID) on delete cascade;

prompt
prompt Creating table FX_AUDIT
prompt =======================
prompt
create table TBICDS.FX_AUDIT
(
  DB_SESSION_ID VARCHAR2(500),
  CLIENT_IP     VARCHAR2(500),
  FX_USER_ID    NUMBER,
  AUDIT_DATE    DATE,
  AUDIT_NAME    VARCHAR2(500),
  AUDIT_DATA    CLOB
)
;
comment on table TBICDS.FX_AUDIT
  is 'Contains an audit of all transactions that occur through the data layer.';
comment on column TBICDS.FX_AUDIT.DB_SESSION_ID
  is 'database session id of the user logged in';
comment on column TBICDS.FX_AUDIT.CLIENT_IP
  is 'client IP of the user logged in';
comment on column TBICDS.FX_AUDIT.FX_USER_ID
  is 'user id of the user logged in (fk)';
comment on column TBICDS.FX_AUDIT.AUDIT_DATE
  is 'date/time of audit';
comment on column TBICDS.FX_AUDIT.AUDIT_NAME
  is 'name of audit, ie. SP being called';
comment on column TBICDS.FX_AUDIT.AUDIT_DATA
  is 'audit data, ie. paramaters being passed to the SP';

prompt
prompt Creating table FX_IPLOGIN_ATTEMPTS
prompt ==================================
prompt
create table TBICDS.FX_IPLOGIN_ATTEMPTS
(
  CLIENT_IP         VARCHAR2(500),
  LOGIN_ATTEMPTS    NUMBER,
  DATE_LAST_ATTEMPT DATE,
  IS_LOCKED         NUMBER,
  LOCK_PERIOD       NUMBER
)
;
comment on table TBICDS.FX_IPLOGIN_ATTEMPTS
  is 'Contains information related to invalid login attempts by IP';
comment on column TBICDS.FX_IPLOGIN_ATTEMPTS.CLIENT_IP
  is 'IP of the user trying to login';
comment on column TBICDS.FX_IPLOGIN_ATTEMPTS.LOGIN_ATTEMPTS
  is 'Number of attempts by an IP address';
comment on column TBICDS.FX_IPLOGIN_ATTEMPTS.DATE_LAST_ATTEMPT
  is 'Date of last attempt';
comment on column TBICDS.FX_IPLOGIN_ATTEMPTS.IS_LOCKED
  is 'IP is locked';
comment on column TBICDS.FX_IPLOGIN_ATTEMPTS.LOCK_PERIOD
  is 'Time in minutes to lock ip';

prompt
prompt Creating table FX_JOB_STATUS
prompt ============================
prompt
create table TBICDS.FX_JOB_STATUS
(
  JOB_DATE    DATE default sysdate,
  STATUS_CODE NUMBER,
  JOB_STATUS  CLOB,
  JOB_NAME    VARCHAR2(500)
)
;
comment on table TBICDS.FX_JOB_STATUS
  is 'Contains information related to database job statuses.';
comment on column TBICDS.FX_JOB_STATUS.JOB_DATE
  is 'Date/Time job completed';
comment on column TBICDS.FX_JOB_STATUS.STATUS_CODE
  is 'Status of the job: 0=success, other than 0 error code.';
comment on column TBICDS.FX_JOB_STATUS.JOB_STATUS
  is 'Additional information related to the job';
comment on column TBICDS.FX_JOB_STATUS.JOB_NAME
  is 'Name of the job';

prompt
prompt Creating table FX_PAGE_ACCESS
prompt =============================
prompt
create table TBICDS.FX_PAGE_ACCESS
(
  PAGE_NAME    VARCHAR2(255) not null,
  USER_TYPE    NUMBER,
  USER_RIGHTS  NUMBER,
  ACTIVE       NUMBER default 1,
  COMMENTS     VARCHAR2(255),
  IS_LOGGED_IN NUMBER(2) default 1
)
;
comment on table TBICDS.FX_PAGE_ACCESS
  is 'Contains information related to web site page access. All page names must go in this table and appropriate permissions must be set for each page.';
comment on column TBICDS.FX_PAGE_ACCESS.PAGE_NAME
  is 'Name of page (pk)';
comment on column TBICDS.FX_PAGE_ACCESS.USER_TYPE
  is 'User type allowed access to this page';
comment on column TBICDS.FX_PAGE_ACCESS.USER_RIGHTS
  is 'User rights allowed access to this page';
comment on column TBICDS.FX_PAGE_ACCESS.ACTIVE
  is 'Is this page Active';
comment on column TBICDS.FX_PAGE_ACCESS.COMMENTS
  is 'Comments about this page';
comment on column TBICDS.FX_PAGE_ACCESS.IS_LOGGED_IN
  is 'Does the user have to be logged in to access this page';
alter table TBICDS.FX_PAGE_ACCESS
  add constraint PKPAGENAME primary key (PAGE_NAME);

prompt
prompt Creating table FX_RESTRICTED_NAME
prompt =================================
prompt
create table TBICDS.FX_RESTRICTED_NAME
(
  RESTRICTED_NAME VARCHAR2(50) not null
)
;
comment on table TBICDS.FX_RESTRICTED_NAME
  is 'Contains a list of items not allowed as part of a password, not applicable to this project';
comment on column TBICDS.FX_RESTRICTED_NAME.RESTRICTED_NAME
  is 'Text not allowed as part of a password';
create index TBICDS.RESTRICTED_NAME_NDX01 on TBICDS.FX_RESTRICTED_NAME (RESTRICTED_NAME);

prompt
prompt Creating table FX_SEC_QUESTIONS
prompt ===============================
prompt
create table TBICDS.FX_SEC_QUESTIONS
(
  FX_USER_ID      NUMBER,
  QUESTION_ID_1   NUMBER,
  ANSWER_1        VARCHAR2(255),
  QUESTION_ID_2   NUMBER,
  ANSWER_2        VARCHAR2(255),
  QUESTION_ID_3   NUMBER,
  ANSWER_3        VARCHAR2(255),
  ANSWER_ATTEMPTS NUMBER default 0,
  LAST_UPDATED    DATE
)
;

prompt
prompt Creating table FX_SESSION
prompt =========================
prompt
create table TBICDS.FX_SESSION
(
  WEB_SESSION_ID   VARCHAR2(500),
  DB_SESSION_ID    VARCHAR2(500),
  DATE_CREATED     VARCHAR2(500),
  DATE_LAST_ACTION VARCHAR2(500),
  FX_USER_ID       NUMBER,
  EXPIRED          NUMBER,
  CLIENT_IP        VARCHAR2(500)
)
;
comment on table TBICDS.FX_SESSION
  is 'Contains information related to a users session. Each time the user logs in to the site a record is created in this table.';
comment on column TBICDS.FX_SESSION.WEB_SESSION_ID
  is 'Web session ID (pk)';
comment on column TBICDS.FX_SESSION.DB_SESSION_ID
  is 'Database session ID (pk)';
comment on column TBICDS.FX_SESSION.DATE_CREATED
  is 'Date/time created (pk)';
comment on column TBICDS.FX_SESSION.DATE_LAST_ACTION
  is 'Date/time of last action';
comment on column TBICDS.FX_SESSION.FX_USER_ID
  is 'User ID of this session (fk)';
comment on column TBICDS.FX_SESSION.EXPIRED
  is 'Is this session expired';
comment on column TBICDS.FX_SESSION.CLIENT_IP
  is 'IP address of the user';

prompt
prompt Creating table FX_SESSION_VALUE
prompt ===============================
prompt
create table TBICDS.FX_SESSION_VALUE
(
  DB_SESSION_ID    VARCHAR2(1500),
  DB_SESSION_KEY   VARCHAR2(500),
  DB_SESSION_VALUE VARCHAR2(4000),
  CLIENT_IP        VARCHAR2(500)
)
;
comment on table TBICDS.FX_SESSION_VALUE
  is 'Contains information cached by a user for use throughout the users session.';
comment on column TBICDS.FX_SESSION_VALUE.DB_SESSION_ID
  is 'Database session ID';
comment on column TBICDS.FX_SESSION_VALUE.DB_SESSION_KEY
  is 'Key used to access the cached value';
comment on column TBICDS.FX_SESSION_VALUE.DB_SESSION_VALUE
  is 'Value of the item cached';
comment on column TBICDS.FX_SESSION_VALUE.CLIENT_IP
  is 'IP address of the user that cached the value';

prompt
prompt Creating table FX_SETTINGS
prompt ==========================
prompt
create table TBICDS.FX_SETTINGS
(
  MAIL_SMTP_HOST               VARCHAR2(4000),
  MAIL_SMTP_SENDER             VARCHAR2(4000),
  MAIL_SMTP_PORT               NUMBER,
  SITE_URL                     VARCHAR2(4000),
  NOTIFY_EMAIL                 VARCHAR2(4000),
  HAS_MILITARY_DETAIL          NUMBER(1) default 0,
  HAS_PATIENT_SUPERVISOR_INPUT NUMBER(1) default 0,
  HAS_PATIENT_INSURANCE        NUMBER(1) default 0,
  BRANCH_OF_SERVICE            NUMBER(1) default 0,
  TEXTING_HOST                 VARCHAR2(4000),
  TEXTING_PORT                 NUMBER,
  TEXTING_USER                 VARCHAR2(4000),
  TEXTING_PSWD                 VARCHAR2(4000),
  ORA_WIN_DIR                  VARCHAR2(4000)
)
;
comment on column TBICDS.FX_SETTINGS.MAIL_SMTP_HOST
  is 'SMTP Mail Server IP Address';
comment on column TBICDS.FX_SETTINGS.MAIL_SMTP_SENDER
  is 'Sender Email Address To Be Used In the Email To Field on Notification Emails';
comment on column TBICDS.FX_SETTINGS.MAIL_SMTP_PORT
  is 'SMTP Mail Server Port ID';
comment on column TBICDS.FX_SETTINGS.SITE_URL
  is 'Website URL';
comment on column TBICDS.FX_SETTINGS.NOTIFY_EMAIL
  is 'Email Address of Sys Admin Receiving Email Notifications';
comment on column TBICDS.FX_SETTINGS.HAS_MILITARY_DETAIL
  is 'Flag Indicating Whether The Military Detail Tab Should be Shown';
comment on column TBICDS.FX_SETTINGS.HAS_PATIENT_SUPERVISOR_INPUT
  is 'Flag Indicating Whether The Supervisor Input Tab should be Shown';
comment on column TBICDS.FX_SETTINGS.HAS_PATIENT_INSURANCE
  is 'Flag Indicating Whether Patient Insurance Tab should be Shown';
comment on column TBICDS.FX_SETTINGS.BRANCH_OF_SERVICE
  is 'Field Identifying Patient''s Branch of Service - AirForce  = 1,
  Army = 2,
  Marines = 3,
  Navy = 4,
  Commercial = 5';
comment on column TBICDS.FX_SETTINGS.TEXTING_HOST
  is 'Text Message Server IP Address';
comment on column TBICDS.FX_SETTINGS.TEXTING_PORT
  is 'Text Message Server Port ID';
comment on column TBICDS.FX_SETTINGS.TEXTING_USER
  is 'Text Message Username';
comment on column TBICDS.FX_SETTINGS.TEXTING_PSWD
  is 'Text Message Password';

prompt
prompt Creating table FX_USER_RIGHTS
prompt =============================
prompt
create table TBICDS.FX_USER_RIGHTS
(
  FX_USER_ID  NUMBER(11),
  USER_RIGHTS NUMBER(32),
  READ_ONLY   NUMBER(32),
  USER_TYPE   NUMBER(32)
)
;
comment on table TBICDS.FX_USER_RIGHTS
  is 'Contains information related to user rights';
comment on column TBICDS.FX_USER_RIGHTS.FX_USER_ID
  is 'User ID (fk)';
comment on column TBICDS.FX_USER_RIGHTS.USER_RIGHTS
  is 'User rights foir this user';
comment on column TBICDS.FX_USER_RIGHTS.READ_ONLY
  is 'User has read only access: 0 = No, 1 = Yes';
comment on column TBICDS.FX_USER_RIGHTS.USER_TYPE
  is 'Type of user';

prompt
prompt Creating table INTAKE_FLAGS
prompt ===========================
prompt
create table TBICDS.INTAKE_FLAGS
(
  FLAG_ID            NUMBER(11) default 0 not null,
  MID                NUMBER(5) default 0 not null,
  SESSION_FLAG_TX    VARCHAR2(4000) not null,
  VISIBLE            NUMBER(3),
  SESSION_FLAG_ED    VARCHAR2(4000),
  CALC_TYPE          VARCHAR2(10),
  CALC_VAR           VARCHAR2(4000),
  CALCULATED         NUMBER(11) default 0,
  SEVERITY_CODE      NUMBER(11) default 0,
  FLAG_TYPE_ID       NUMBER default 0 not null,
  IDENTIFIER         VARCHAR2(50),
  SESSION_FLAG_LIST  VARCHAR2(4000),
  PRIORITY           NUMBER(2),
  FLAG_TARGET_ID     NUMBER(3),
  RISK_FACTOR_ID     NUMBER(4),
  TID                NUMBER(2),
  REPORT_TYPE_ID     NUMBER(2),
  FLAG_GROUP         NUMBER(2),
  ALTERNATE_LANGUAGE VARCHAR2(4000),
  FLAG_SERIES        NUMBER(10),
  ALT_LANG_CALC_VAR  VARCHAR2(4000)
)
;
comment on table TBICDS.INTAKE_FLAGS
  is 'Contains the flags triggered by an instrument session';
comment on column TBICDS.INTAKE_FLAGS.FLAG_ID
  is 'Flag ID (pk)';
comment on column TBICDS.INTAKE_FLAGS.MID
  is 'Module ID';
comment on column TBICDS.INTAKE_FLAGS.SESSION_FLAG_TX
  is 'Flag text';
comment on column TBICDS.INTAKE_FLAGS.VISIBLE
  is 'Id this flag visible on reports';
comment on column TBICDS.INTAKE_FLAGS.SESSION_FLAG_ED
  is 'Education for this flag';
comment on column TBICDS.INTAKE_FLAGS.CALC_TYPE
  is 'Flag calculation type';
comment on column TBICDS.INTAKE_FLAGS.CALC_VAR
  is 'Variable name for this flag';
comment on column TBICDS.INTAKE_FLAGS.CALCULATED
  is 'Is this flag calculated';
comment on column TBICDS.INTAKE_FLAGS.SEVERITY_CODE
  is 'Flag severity code';
comment on column TBICDS.INTAKE_FLAGS.FLAG_TYPE_ID
  is 'Flag type id: 99 is assessment completed';
comment on column TBICDS.INTAKE_FLAGS.IDENTIFIER
  is 'Flag identifier';
comment on column TBICDS.INTAKE_FLAGS.SESSION_FLAG_LIST
  is 'N/A';
comment on column TBICDS.INTAKE_FLAGS.PRIORITY
  is 'Flag priority';
comment on column TBICDS.INTAKE_FLAGS.FLAG_TARGET_ID
  is 'Flag target';
comment on column TBICDS.INTAKE_FLAGS.RISK_FACTOR_ID
  is 'N/A';
comment on column TBICDS.INTAKE_FLAGS.TID
  is 'Topic ID';
comment on column TBICDS.INTAKE_FLAGS.REPORT_TYPE_ID
  is 'Repoty type ID:  1 = patient, 2 = provider bullet, 3 = provider full';
comment on column TBICDS.INTAKE_FLAGS.FLAG_GROUP
  is 'Associates related flags';
comment on column TBICDS.INTAKE_FLAGS.ALTERNATE_LANGUAGE
  is 'N/A';
comment on column TBICDS.INTAKE_FLAGS.FLAG_SERIES
  is 'N/A';
comment on column TBICDS.INTAKE_FLAGS.ALT_LANG_CALC_VAR
  is 'N/A';
alter table TBICDS.INTAKE_FLAGS
  add constraint PRIMARYKEY00018 primary key (FLAG_ID);
create index TBICDS.MID00005 on TBICDS.INTAKE_FLAGS (MID);

prompt
prompt Creating table INTAKE_LOGICVAR_SQL
prompt ==================================
prompt
create table TBICDS.INTAKE_LOGICVAR_SQL
(
  VAR_ID     NUMBER(5) not null,
  IDENTIFIER VARCHAR2(25) not null,
  LOAD_SQL   VARCHAR2(4000)
)
;
comment on column TBICDS.INTAKE_LOGICVAR_SQL.IDENTIFIER
  is 'DO NOT CHANGE THESE; if you must change these identifiers you will have to update all logic expressions that use them, all intake flags that use them and the hard coded strings in equation.cpp in iqtoolkit';
alter table TBICDS.INTAKE_LOGICVAR_SQL
  add constraint LOGICSQL_PK primary key (VAR_ID);
alter table TBICDS.INTAKE_LOGICVAR_SQL
  add constraint LOGICSQL_UNIQUE unique (IDENTIFIER);

prompt
prompt Creating table INTAKE_MODULE_DESCRIPTION
prompt ========================================
prompt
create table TBICDS.INTAKE_MODULE_DESCRIPTION
(
  MID              NUMBER,
  SCORABLE         NUMBER,
  MIN_SCORE        NUMBER,
  MAX_SCORE        NUMBER,
  DEVISION_SLICE   NUMBER,
  NUMBER_OF_SLICES NUMBER
)
;
comment on column TBICDS.INTAKE_MODULE_DESCRIPTION.MID
  is 'module id';
comment on column TBICDS.INTAKE_MODULE_DESCRIPTION.SCORABLE
  is 'is this module scorable';
comment on column TBICDS.INTAKE_MODULE_DESCRIPTION.MIN_SCORE
  is 'minimum score';
comment on column TBICDS.INTAKE_MODULE_DESCRIPTION.MAX_SCORE
  is 'maximum score';
comment on column TBICDS.INTAKE_MODULE_DESCRIPTION.DEVISION_SLICE
  is 'slice/devision between min and max';
comment on column TBICDS.INTAKE_MODULE_DESCRIPTION.NUMBER_OF_SLICES
  is 'number of slices';

prompt
prompt Creating table INTAKE_MODULE_GROUP
prompt ==================================
prompt
create table TBICDS.INTAKE_MODULE_GROUP
(
  MODULE_GROUP_ID      NUMBER,
  MODULE_GROUP_DESCR   VARCHAR2(255),
  SORT_ORDER           NUMBER,
  DESCRIPTION          VARCHAR2(4000),
  EVENT_ID             NUMBER(4),
  ACTIVE               NUMBER(2) default 1,
  STAT_MODALITY_ID     NUMBER(4),
  MODULE_GROUP_TYPE_ID NUMBER
)
;
comment on table TBICDS.INTAKE_MODULE_GROUP
  is 'Contains information related to an Instrument group';
comment on column TBICDS.INTAKE_MODULE_GROUP.MODULE_GROUP_ID
  is 'Module group ID (pk)';
comment on column TBICDS.INTAKE_MODULE_GROUP.MODULE_GROUP_DESCR
  is 'Module group description';
comment on column TBICDS.INTAKE_MODULE_GROUP.SORT_ORDER
  is 'Sort order for display';
comment on column TBICDS.INTAKE_MODULE_GROUP.DESCRIPTION
  is 'N/A';
comment on column TBICDS.INTAKE_MODULE_GROUP.EVENT_ID
  is 'Event ID (fk)';
comment on column TBICDS.INTAKE_MODULE_GROUP.ACTIVE
  is 'Is this group active';
comment on column TBICDS.INTAKE_MODULE_GROUP.STAT_MODALITY_ID
  is 'Modality';
comment on column TBICDS.INTAKE_MODULE_GROUP.MODULE_GROUP_TYPE_ID
  is 'Module group type (fk)';

prompt
prompt Creating table INTAKE_MODULE_GROUP_MID
prompt ======================================
prompt
create table TBICDS.INTAKE_MODULE_GROUP_MID
(
  MODULE_GROUP_ID NUMBER,
  MID             NUMBER,
  SORT_ORDER      NUMBER
)
;
comment on table TBICDS.INTAKE_MODULE_GROUP_MID
  is 'Contains information related to an Instrument groups instruments';
comment on column TBICDS.INTAKE_MODULE_GROUP_MID.MODULE_GROUP_ID
  is 'Module group id (pk)';
comment on column TBICDS.INTAKE_MODULE_GROUP_MID.MID
  is 'Modle ID (pk)';
comment on column TBICDS.INTAKE_MODULE_GROUP_MID.SORT_ORDER
  is 'Sort order for display';

prompt
prompt Creating table INTAKE_MODULE_GROUP_TYPE
prompt =======================================
prompt
create table TBICDS.INTAKE_MODULE_GROUP_TYPE
(
  MODULE_GROUP_TYPE_ID NUMBER not null,
  MODULE_GROUP_DESCR   VARCHAR2(1024),
  SORT_ORDER           NUMBER(5),
  ACTIVE               NUMBER(1) default 1
)
;
comment on table TBICDS.INTAKE_MODULE_GROUP_TYPE
  is 'Contains information related to an Instrument group type';
comment on column TBICDS.INTAKE_MODULE_GROUP_TYPE.MODULE_GROUP_TYPE_ID
  is 'Module group type ID (pk)';
comment on column TBICDS.INTAKE_MODULE_GROUP_TYPE.MODULE_GROUP_DESCR
  is 'Group type description';
comment on column TBICDS.INTAKE_MODULE_GROUP_TYPE.SORT_ORDER
  is 'Sort order for display';
comment on column TBICDS.INTAKE_MODULE_GROUP_TYPE.ACTIVE
  is 'Is the type active for use';
alter table TBICDS.INTAKE_MODULE_GROUP_TYPE
  add constraint PK_MODULE_GROUP_TYPE_ID primary key (MODULE_GROUP_TYPE_ID);

prompt
prompt Creating table INTAKE_MODULE_VARIABLES
prompt ======================================
prompt
create table TBICDS.INTAKE_MODULE_VARIABLES
(
  VAR_ID NUMBER,
  MID    NUMBER
)
;
comment on table TBICDS.INTAKE_MODULE_VARIABLES
  is 'Contains information related to Instrument variables';
comment on column TBICDS.INTAKE_MODULE_VARIABLES.VAR_ID
  is 'Variable ID ';
comment on column TBICDS.INTAKE_MODULE_VARIABLES.MID
  is 'Module ID (fk)';

prompt
prompt Creating table INTAKE_TOPIC
prompt ===========================
prompt
create table TBICDS.INTAKE_TOPIC
(
  MID                    NUMBER(5) default 0 not null,
  TID                    NUMBER(5) not null,
  TOPIC                  VARCHAR2(4000) not null,
  DEL_TACTION            VARCHAR2(10),
  ACTIVE                 NUMBER(5) not null,
  DEL_ALTERNATE_LANGUAGE VARCHAR2(1024),
  DEL_TOPIC_IMAGE        VARCHAR2(255)
)
;
comment on table TBICDS.INTAKE_TOPIC
  is 'Contains information related to Instrument topics';
comment on column TBICDS.INTAKE_TOPIC.MID
  is 'Module ID (pk)';
comment on column TBICDS.INTAKE_TOPIC.TID
  is 'Topic ID (pk)';
comment on column TBICDS.INTAKE_TOPIC.TOPIC
  is 'Topic text';
comment on column TBICDS.INTAKE_TOPIC.DEL_TACTION
  is 'N/A';
comment on column TBICDS.INTAKE_TOPIC.ACTIVE
  is 'Is this topic active';
comment on column TBICDS.INTAKE_TOPIC.DEL_ALTERNATE_LANGUAGE
  is 'N/A';
comment on column TBICDS.INTAKE_TOPIC.DEL_TOPIC_IMAGE
  is 'N/A added to support patient portal';
alter table TBICDS.INTAKE_TOPIC
  add constraint PRIMARYKEY00106 primary key (MID, TID);
alter table TBICDS.INTAKE_TOPIC
  add foreign key (MID)
  references TBICDS.INTAKE_MODULE (MID)
  disable;
create index TBICDS.INTAKE_MODULEINTAKE_TOPIC00000 on TBICDS.INTAKE_TOPIC (MID);

prompt
prompt Creating table INTAKE_QUESTION
prompt ==============================
prompt
create table TBICDS.INTAKE_QUESTION
(
  MID             NUMBER(5) default 0 not null,
  TID             NUMBER(5) not null,
  QID             NUMBER(5) default 0 not null,
  QUESTION        VARCHAR2(4000),
  ACTIVE          NUMBER,
  RESPONSES_POS   NUMBER(2) default 1,
  RESPONSE_LAYOUT NUMBER(2) default 1,
  CDE_ID          VARCHAR2(20),
  REQUIRED        NUMBER default 1
)
;
comment on table TBICDS.INTAKE_QUESTION
  is 'Contains information related to Instrument questions';
comment on column TBICDS.INTAKE_QUESTION.MID
  is 'Module identifier (pk)';
comment on column TBICDS.INTAKE_QUESTION.TID
  is 'Topic Identifier (pk)';
comment on column TBICDS.INTAKE_QUESTION.QID
  is 'Question Identifier (pk)';
comment on column TBICDS.INTAKE_QUESTION.QUESTION
  is 'Question Text in english';
comment on column TBICDS.INTAKE_QUESTION.ACTIVE
  is '0 to decomission a question';
comment on column TBICDS.INTAKE_QUESTION.RESPONSES_POS
  is 'Responses Layout. 1: Vertical, 2: Horizontal';
comment on column TBICDS.INTAKE_QUESTION.RESPONSE_LAYOUT
  is '1: UL; 2: TABLE';
comment on column TBICDS.INTAKE_QUESTION.CDE_ID
  is 'CDE mapping id';
comment on column TBICDS.INTAKE_QUESTION.REQUIRED
  is '0 = Not required, 1 = Required (only when editable mode is off (INTAKE_MODULE.EDITABLE = 0))';
alter table TBICDS.INTAKE_QUESTION
  add constraint PRIMARYKEY00104 primary key (MID, TID, QID);
alter table TBICDS.INTAKE_QUESTION
  add foreign key (MID, TID)
  references TBICDS.INTAKE_TOPIC (MID, TID)
  disable;
create index TBICDS.INTAKE_TOPICINTAKE_QUEST00000 on TBICDS.INTAKE_QUESTION (MID, TID);

prompt
prompt Creating table INTAKE_RESPONSE
prompt ==============================
prompt
create table TBICDS.INTAKE_RESPONSE
(
  RID                NUMBER(5) not null,
  MID                NUMBER(5) default 0 not null,
  TID                NUMBER(5) not null,
  QID                NUMBER(5) not null,
  RESPONSE           VARCHAR2(500) not null,
  DISPLAY_TYPE       NUMBER(5) default 0,
  RESPONSE_TYPE      NUMBER(5) default 0,
  ACTIVE             NUMBER,
  UNIT               VARCHAR2(80),
  MAXLENGTH          NUMBER,
  MASK               VARCHAR2(128),
  SKIP_SHOW          VARCHAR2(1200),
  SKIP_HIDE          VARCHAR2(1200),
  LABEL_POS          NUMBER(1) default 1,
  RESPONSE_GROUP     NUMBER(5) default 1,
  SCORE_VALUE        VARCHAR2(64),
  STAT_LOAD_TABLE    VARCHAR2(80),
  STAT_LOAD_FIELD    VARCHAR2(80),
  STAT_LOAD_FILTER   VARCHAR2(4000),
  STAT_LOAD_TABLE_ID VARCHAR2(80),
  IDENTIFIER         VARCHAR2(24),
  CDE_ID             VARCHAR2(20)
)
;
comment on table TBICDS.INTAKE_RESPONSE
  is 'Contains information related to Instrument question responses';
comment on column TBICDS.INTAKE_RESPONSE.RID
  is 'Response Identifier. Unique by Module (pk)';
comment on column TBICDS.INTAKE_RESPONSE.MID
  is 'Module Identifier (pk)';
comment on column TBICDS.INTAKE_RESPONSE.TID
  is 'Topic Identifier (fk)';
comment on column TBICDS.INTAKE_RESPONSE.QID
  is 'Question Identifier (fk)';
comment on column TBICDS.INTAKE_RESPONSE.RESPONSE
  is 'Response text';
comment on column TBICDS.INTAKE_RESPONSE.DISPLAY_TYPE
  is 'Type of object that will be displayed for the response: RADIO		= 1;
CHECK		= 2;
TEXT		= 3;
COMBO BOX	= 4;
DATE		= 5;
HEIGHT		= 6;
WEIGHT		= 7;
LIST		= 8;
DATETIME	= 9;
BMI		= 10;
TITLE		= 11;
MONTHYEAR	= 12;
DUALCHOICE	= 13;
TRICHOICE	= 14;
TRICHOICETITLE = 15;
MEDBAR		= 16;
PROVENTRYBAR	= 17;
ALLERGYBAR	= 18;
FAMILYHXBAR	= 19;
COMBOHEIGHT	= 20;
DATEPICKER   	= 21;
SLIDER/COMBO   	= 22;
NONEOFABOVE	= 99;
BLANK_SPACER = 2000;';
comment on column TBICDS.INTAKE_RESPONSE.RESPONSE_TYPE
  is 'BOOL	= 1;
INTEGER = 2;
TEXT	= 3;
DATE	= 4;
PARSED	= 5;';
comment on column TBICDS.INTAKE_RESPONSE.ACTIVE
  is 'Is this response active';
comment on column TBICDS.INTAKE_RESPONSE.UNIT
  is 'describes the unit of the response e.g. Pounds, inches, etc.';
comment on column TBICDS.INTAKE_RESPONSE.MAXLENGTH
  is 'max length of this response';
comment on column TBICDS.INTAKE_RESPONSE.MASK
  is 'Mask used for display';
comment on column TBICDS.INTAKE_RESPONSE.SKIP_SHOW
  is 'Question(s) to SHOW when the status of the response is CLICKED';
comment on column TBICDS.INTAKE_RESPONSE.SKIP_HIDE
  is 'Question(s) to HIDE when the status of the response is CLICKED';
comment on column TBICDS.INTAKE_RESPONSE.LABEL_POS
  is 'In relation to the control, where the label is positioned: 0: not shown, 1: left, 2 right';
comment on column TBICDS.INTAKE_RESPONSE.RESPONSE_GROUP
  is 'Response group';
comment on column TBICDS.INTAKE_RESPONSE.SCORE_VALUE
  is 'Score value';
comment on column TBICDS.INTAKE_RESPONSE.STAT_LOAD_TABLE
  is 'Table to load this response from';
comment on column TBICDS.INTAKE_RESPONSE.STAT_LOAD_FIELD
  is 'Field to load this resposne from';
comment on column TBICDS.INTAKE_RESPONSE.STAT_LOAD_FILTER
  is 'Filter used to load this response';
comment on column TBICDS.INTAKE_RESPONSE.STAT_LOAD_TABLE_ID
  is 'ID field name from the table used to load this response';
comment on column TBICDS.INTAKE_RESPONSE.IDENTIFIER
  is 'Identifier';
comment on column TBICDS.INTAKE_RESPONSE.CDE_ID
  is 'CDE mapping id';
alter table TBICDS.INTAKE_RESPONSE
  add constraint INTAKE_RESPONSE_KEY_PK primary key (RID, MID);
alter table TBICDS.INTAKE_RESPONSE
  add constraint INTAKE_RESPONSE_KEY_FK01 foreign key (MID, TID, QID)
  references TBICDS.INTAKE_QUESTION (MID, TID, QID)
  disable;
create index TBICDS.INTAKE_QUESTIONINTAKE_RE00000 on TBICDS.INTAKE_RESPONSE (MID, TID, QID);
create index TBICDS.MID00012 on TBICDS.INTAKE_RESPONSE (MID);
create index TBICDS.QID00002 on TBICDS.INTAKE_RESPONSE (QID);
create index TBICDS.TID00002 on TBICDS.INTAKE_RESPONSE (TID);

prompt
prompt Creating table INTAKE_STATIC_DATA
prompt =================================
prompt
create table TBICDS.INTAKE_STATIC_DATA
(
  DATA_ID     NUMBER(5) not null,
  DATA_ITEM   NUMBER(5) not null,
  MID         NUMBER(5) not null,
  DATA_VALUE  VARCHAR2(80),
  SCORE_VALUE NUMBER(5),
  ACTIVE      NUMBER(5)
)
;
comment on table TBICDS.INTAKE_STATIC_DATA
  is 'Contains information related to static data displayed from an instrument.';
comment on column TBICDS.INTAKE_STATIC_DATA.DATA_ID
  is 'Data ID (pk)';
comment on column TBICDS.INTAKE_STATIC_DATA.DATA_ITEM
  is 'Data Item (pk)';
comment on column TBICDS.INTAKE_STATIC_DATA.MID
  is 'Instrument ID (pk)';
comment on column TBICDS.INTAKE_STATIC_DATA.DATA_VALUE
  is 'Data value';
comment on column TBICDS.INTAKE_STATIC_DATA.SCORE_VALUE
  is 'Score value';
comment on column TBICDS.INTAKE_STATIC_DATA.ACTIVE
  is 'Active';
alter table TBICDS.INTAKE_STATIC_DATA
  add constraint PK_STATIC_DATA primary key (DATA_ITEM, DATA_ID, MID);

prompt
prompt Creating table PATIENT_ADMISSION
prompt ================================
prompt
create table TBICDS.PATIENT_ADMISSION
(
  REGION_ID                 NUMBER,
  SITE_ID                   NUMBER,
  DFN                       VARCHAR2(255),
  ADMIT_LOCATION_ID         NUMBER,
  ADMIT_LOCATION_NAME       VARCHAR2(255),
  ADMIT_TYPE                VARCHAR2(255),
  ADMIT_TIMESTAMP           VARCHAR2(255),
  ADMIT_DISCHARGE_TIMESTAMP VARCHAR2(255),
  ADMIT_DATETIME            DATE
)
;
comment on table TBICDS.PATIENT_ADMISSION
  is 'Contains admission information transferred from MDWS';
comment on column TBICDS.PATIENT_ADMISSION.REGION_ID
  is 'Region id (pk)';
comment on column TBICDS.PATIENT_ADMISSION.SITE_ID
  is 'Site id (pk)';
comment on column TBICDS.PATIENT_ADMISSION.DFN
  is 'Patient dfn (pk)';
comment on column TBICDS.PATIENT_ADMISSION.ADMIT_LOCATION_ID
  is 'Location ID';
comment on column TBICDS.PATIENT_ADMISSION.ADMIT_LOCATION_NAME
  is 'Location Name';
comment on column TBICDS.PATIENT_ADMISSION.ADMIT_TYPE
  is 'Admission type';
comment on column TBICDS.PATIENT_ADMISSION.ADMIT_TIMESTAMP
  is 'Admission timestamp';
comment on column TBICDS.PATIENT_ADMISSION.ADMIT_DISCHARGE_TIMESTAMP
  is 'Admission discharge timestamp';
comment on column TBICDS.PATIENT_ADMISSION.ADMIT_DATETIME
  is 'Admission date/time';

prompt
prompt Creating table PATIENT_APPOINTMENT
prompt ==================================
prompt
create table TBICDS.PATIENT_APPOINTMENT
(
  REGION_ID           NUMBER,
  SITE_ID             NUMBER,
  APPT_ID             VARCHAR2(128),
  DFN                 VARCHAR2(255),
  APPT_CLINIC_ID      NUMBER,
  APPT_SITE_ID        NUMBER,
  APPT_CURRENT_STATUS VARCHAR2(128),
  APPT_PURPOSE        VARCHAR2(128),
  APPT_STATUS         VARCHAR2(128),
  APPT_TEXT           VARCHAR2(255),
  APPT_TIMESTAMP      VARCHAR2(128),
  APPT_TITLE          VARCHAR2(255),
  APPT_TYPE           VARCHAR2(50),
  APPT_VISIT_ID       VARCHAR2(128),
  APPT_DATETIME       DATE
)
;
comment on table TBICDS.PATIENT_APPOINTMENT
  is 'Contains appointment information transferred from MDWS';
comment on column TBICDS.PATIENT_APPOINTMENT.REGION_ID
  is 'Region id (pk)';
comment on column TBICDS.PATIENT_APPOINTMENT.SITE_ID
  is 'Site id (pk)';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_ID
  is 'Appt id (pk)';
comment on column TBICDS.PATIENT_APPOINTMENT.DFN
  is 'Patient dfn (pk)';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_CLINIC_ID
  is 'Appointment clinic id (fk)';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_SITE_ID
  is 'Appointment site id';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_CURRENT_STATUS
  is 'Appointment status';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_PURPOSE
  is 'Appointment purpose';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_STATUS
  is 'Appointment status';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_TEXT
  is 'Appointment text';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_TIMESTAMP
  is 'Appointment timestamp';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_TITLE
  is 'Appointment title';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_TYPE
  is 'Appointment type';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_VISIT_ID
  is 'Appointment visit id';
comment on column TBICDS.PATIENT_APPOINTMENT.APPT_DATETIME
  is 'Appointment date/time';

prompt
prompt Creating type TYP_OBJ_RPT_CDE_PAT
prompt =================================
prompt
create or replace type tbicds.TYP_OBJ_RPT_CDE_PAT is object (
   c1 varchar2(128),
   c2 varchar2(128),
   c3 varchar2(128),
   c4 varchar2(128),
   c5 varchar2(128),
   c6 varchar2(128),
   c7 varchar2(128),
   c8 varchar2(128),
   c9 varchar2(128),
   c10 varchar2(128),
   c11 varchar2(128),
   c12 varchar2(128),
   c13 varchar2(128),
   c14 varchar2(128),
   c15 varchar2(128),
   c16 varchar2(128),
   c17 varchar2(128),
   c18 varchar2(128),
   c19 varchar2(128),
   c20 varchar2(128),
   c21 varchar2(128),
   c22 varchar2(128),
   c23 varchar2(128),
   c24 varchar2(128),
   c25 varchar2(128),
   c26 varchar2(128),
   c27 varchar2(128),
   c28 varchar2(128),
   c29 varchar2(128),
   c30 varchar2(128),
   c31 varchar2(128),
   c32 varchar2(128),
   c33 varchar2(128),
   c34 varchar2(128),
   c35 varchar2(128),
   c36 varchar2(128),
   c37 varchar2(128),
   c38 varchar2(128),
   c39 varchar2(128),
   c40 varchar2(128),
   c41 varchar2(128),
   c42 varchar2(128),
   c43 varchar2(128),
   c44 varchar2(128),
   c45 varchar2(128),
   c46 varchar2(128),
   c47 varchar2(128),
   c48 varchar2(128),
   c49 varchar2(128),
   c50 varchar2(128),
   c51 varchar2(128),
   c52 varchar2(128),
   c53 varchar2(128),
   c54 varchar2(128),
   c55 varchar2(128),
   c56 varchar2(128),
   c57 varchar2(128),
   c58 varchar2(128),
   c59 varchar2(128),
   c60 varchar2(128),
   c61 varchar2(128),
   c62 varchar2(128),
   c63 varchar2(128),
   c64 varchar2(128),
   c65 varchar2(128),
   c66 varchar2(128),
   c67 varchar2(128),
   c68 varchar2(128),
   c69 varchar2(128),
   c70 varchar2(128),
   c71 varchar2(128),
   c72 varchar2(128),
   c73 varchar2(128),
   c74 varchar2(128),
   c75 varchar2(128),
   c76 varchar2(128),
   c77 varchar2(128),
   c78 varchar2(128),
   c79 varchar2(128),
   c80 varchar2(128),
   c81 varchar2(128),
   c82 varchar2(128),
   c83 varchar2(128),
   c84 varchar2(128),
   c85 varchar2(128),
   c86 varchar2(128),
   c87 varchar2(128),
   c88 varchar2(128),
   c89 varchar2(128),
   c90 varchar2(128),
   c91 varchar2(128),
   c92 varchar2(128),
   c93 varchar2(128),
   c94 varchar2(128),
   c95 varchar2(128),
   c96 varchar2(128),
   c97 varchar2(128),
   c98 varchar2(128),
   c99 varchar2(128),
   c100 varchar2(128),
   c101 varchar2(128),
   c102 varchar2(128),
   c103 varchar2(128),
   c104 varchar2(128),
   c105 varchar2(128),
   c106 varchar2(128),
   c107 varchar2(128),
   c108 varchar2(128),
   c109 varchar2(128),
   c110 varchar2(128),
   c111 varchar2(128),
   c112 varchar2(128),
   c113 varchar2(128),
   c114 varchar2(128),
   c115 varchar2(128),
   c116 varchar2(128),
   c117 varchar2(128),
   c118 varchar2(128),
   c119 varchar2(128),
   c120 varchar2(128),
   c121 varchar2(128),
   c122 varchar2(128),
   c123 varchar2(128),
   c124 varchar2(128),
   c125 varchar2(128),
   c126 varchar2(128),
   c127 varchar2(128),
   c128 varchar2(128),
   c129 varchar2(128),
   c130 varchar2(128),
   c131 varchar2(128),
   c132 varchar2(128),
   c133 varchar2(128),
   c134 varchar2(128),
   c135 varchar2(128),
   c136 varchar2(128),
   c137 varchar2(128),
   c138 varchar2(128),
   c139 varchar2(128),
   c140 varchar2(128),
   c141 varchar2(128),
   c142 varchar2(128),
   c143 varchar2(128),
   c144 varchar2(128),
   c145 varchar2(128),
   c146 varchar2(128),
   c147 varchar2(128),
   c148 varchar2(128),
   c149 varchar2(128),
   c150 varchar2(128),
   c151 varchar2(128),
   c152 varchar2(128),
   c153 varchar2(128),
   c154 varchar2(128),
   c155 varchar2(128),
   c156 varchar2(128),
   c157 varchar2(128),
   c158 varchar2(128),
   c159 varchar2(128),
   c160 varchar2(128),
   c161 varchar2(128),
   c162 varchar2(128),
   c163 varchar2(128),
   c164 varchar2(128),
   c165 varchar2(128),
   c166 varchar2(128),
   c167 varchar2(128),
   c168 varchar2(128),
   c169 varchar2(128),
   c170 varchar2(128),
   c171 varchar2(128),
   c172 varchar2(128),
   c173 varchar2(128),
   c174 varchar2(128),
   c175 varchar2(128),
   c176 varchar2(128),
   c177 varchar2(128),
   c178 varchar2(128),
   c179 varchar2(128),
   c180 varchar2(128),
   c181 varchar2(128),
   c182 varchar2(128),
   c183 varchar2(128),
   c184 varchar2(128),
   c185 varchar2(128),
   c186 varchar2(128),
   c187 varchar2(128),
   c188 varchar2(128),
   c189 varchar2(128),
   c190 varchar2(128),
   c191 varchar2(128),
   c192 varchar2(128),
   c193 varchar2(128),
   c194 varchar2(128),
   c195 varchar2(128),
   c196 varchar2(128),
   c197 varchar2(128),
   c198 varchar2(128),
   c199 varchar2(128),
   c200 varchar2(128),
   CONSTRUCTOR FUNCTION TYP_OBJ_RPT_CDE_PAT RETURN SELF AS RESULT,
   member procedure setValue (pi_nIndex number, pi_vValue varchar2)
   );
/

prompt
prompt Creating table PATIENT_CDE_RPT
prompt ==============================
prompt
create table TBICDS.PATIENT_CDE_RPT
(
  PATIENT_ID   VARCHAR2(50) not null,
  INTAKE_ID    NUMBER(5),
  DATE_UPDATED DATE default sysdate not null,
  RPT_CDE_PAT  TYP_OBJ_RPT_CDE_PAT
)
;
create index TBICDS.PATIENT_CDE_NDX01 on TBICDS.PATIENT_CDE_RPT (PATIENT_ID);
create index TBICDS.PATIENT_CDE_NDX02 on TBICDS.PATIENT_CDE_RPT (DATE_UPDATED);

prompt
prompt Creating table PATIENT_CONSULT
prompt ==============================
prompt
create table TBICDS.PATIENT_CONSULT
(
  REGION_ID         NUMBER,
  SITE_ID           NUMBER,
  DFN               VARCHAR2(255),
  CONSULT_ID        VARCHAR2(128),
  CONSULT_TIMESTAMP VARCHAR2(255),
  CONSULT_STATUS    VARCHAR2(255),
  CONSULT_TITLE     VARCHAR2(255),
  CONSULT_TEXT      VARCHAR2(4000),
  CONSULT_DATETIME  DATE
)
;
comment on column TBICDS.PATIENT_CONSULT.REGION_ID
  is 'region id';
comment on column TBICDS.PATIENT_CONSULT.SITE_ID
  is 'site id';
comment on column TBICDS.PATIENT_CONSULT.DFN
  is 'pat dfn';
comment on column TBICDS.PATIENT_CONSULT.CONSULT_ID
  is 'patient consult id';
comment on column TBICDS.PATIENT_CONSULT.CONSULT_TIMESTAMP
  is 'consult time stamp';
comment on column TBICDS.PATIENT_CONSULT.CONSULT_STATUS
  is 'consult status';
comment on column TBICDS.PATIENT_CONSULT.CONSULT_TITLE
  is 'consult title';
comment on column TBICDS.PATIENT_CONSULT.CONSULT_TEXT
  is 'consult text';
comment on column TBICDS.PATIENT_CONSULT.CONSULT_DATETIME
  is 'consult date time';

prompt
prompt Creating table PATIENT_DEMOGRAPHICS
prompt ===================================
prompt
create table TBICDS.PATIENT_DEMOGRAPHICS
(
  PATIENT_ID               VARCHAR2(50) not null,
  FIRST_NAME               VARCHAR2(128) not null,
  MI                       VARCHAR2(128),
  LAST_NAME                VARCHAR2(128) not null,
  SSN                      VARCHAR2(128),
  GENDER                   VARCHAR2(128),
  MARITAL_STATUS_ID        NUMBER(5) default 0,
  DOB                      VARCHAR2(128),
  EDUCATION_LEVEL_ID       NUMBER(5) default 0,
  PROVIDER_ID              VARCHAR2(50),
  ADDRESS1                 VARCHAR2(80),
  ADDRESS2                 VARCHAR2(80),
  CITY                     VARCHAR2(50),
  POSTAL_CODE              VARCHAR2(50),
  HOMEPHONE                VARCHAR2(20),
  WORKPHONE                VARCHAR2(20),
  EMAIL                    VARCHAR2(128),
  STATE_ID                 NUMBER(11) default 0,
  FX_USER_ID               NUMBER,
  LAST_UPDATED             DATE,
  LAST_UPDATED_BY          NUMBER,
  PORTAL_USER_ID           NUMBER(11),
  WRK_PHONE_CALL           NUMBER default 0,
  HOME_PHONE_CALL          NUMBER default 0,
  HOME_PHONE_MSG           NUMBER default 0,
  EMAIL_MSG                NUMBER default 0,
  CELLPHONE                VARCHAR2(20),
  CELL_PHONE_CALL          NUMBER default 0,
  DFN                      VARCHAR2(255),
  REGION_ID                NUMBER,
  SITE_ID                  NUMBER,
  PREFERRED_LANGUAGE_ID    NUMBER,
  PREFERRED_LANGUAGE_OTHER VARCHAR2(30),
  DUTY_STATUS_ID           NUMBER,
  HAND_PREFERENCE_ID       NUMBER
)
;
comment on table TBICDS.PATIENT_DEMOGRAPHICS
  is 'Contains patient demographic information. Some information is transferred from MDWS.';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.PATIENT_ID
  is 'Patient ID (pk)';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.FIRST_NAME
  is 'Patient''s first name';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.MI
  is 'Patient''s middle initial';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.LAST_NAME
  is 'Patient''s last name';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.SSN
  is 'Patient''s SSN';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.GENDER
  is 'Patient''s gender';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.MARITAL_STATUS_ID
  is 'Patient''s marital status ID';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.DOB
  is 'Patient''s DOB';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.EDUCATION_LEVEL_ID
  is 'Patient''s education level';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.PROVIDER_ID
  is 'Provider ID who first looked up the patient';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.ADDRESS1
  is 'Patient''s address1';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.ADDRESS2
  is 'Patient''s address2';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.CITY
  is 'Patient''s city';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.POSTAL_CODE
  is 'Patient''s postal code';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.HOMEPHONE
  is 'Patient''s home phone';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.WORKPHONE
  is 'Patient''s work phone';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.EMAIL
  is 'Patient''s email';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.STATE_ID
  is 'Patient''s state id (fk)';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.FX_USER_ID
  is 'Patient''s FX user id if patient has a login account';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.LAST_UPDATED
  is 'date last updated';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.LAST_UPDATED_BY
  is 'last updated by';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.PORTAL_USER_ID
  is 'Patient''s portal user id';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.WRK_PHONE_CALL
  is 'OK to call work phone';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.HOME_PHONE_CALL
  is 'OK to call home phone';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.HOME_PHONE_MSG
  is 'OK to leave voice message';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.EMAIL_MSG
  is 'OK to send email';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.CELLPHONE
  is 'Patient''s cell phone';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.CELL_PHONE_CALL
  is 'OK to call cell phone';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.DFN
  is 'MDWS patient dfn';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.REGION_ID
  is 'MDWS region_id (fk)';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.SITE_ID
  is 'MDWS site id (fk)';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.PREFERRED_LANGUAGE_ID
  is 'Patient''s preferred language (fk to stat_data_collection, _PREFERRED_LANGUAGE subset)';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.PREFERRED_LANGUAGE_OTHER
  is 'Patient''s other preferred language';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.DUTY_STATUS_ID
  is 'Patient''s duty status id (fk to stat_data_collection, _DUTY_STATUS subset)';
comment on column TBICDS.PATIENT_DEMOGRAPHICS.HAND_PREFERENCE_ID
  is 'Patient''s hand preference id (fk to stat_data_collection, _HAND_PREFERENCE subset)';
alter table TBICDS.PATIENT_DEMOGRAPHICS
  add constraint PK_PATIENT primary key (PATIENT_ID);
create index TBICDS.EDUCATIONAL_LEVEL_ID on TBICDS.PATIENT_DEMOGRAPHICS (EDUCATION_LEVEL_ID);
create index TBICDS.MARITAL_STATUS_ID on TBICDS.PATIENT_DEMOGRAPHICS (MARITAL_STATUS_ID);
create index TBICDS.POSTAL_CODE_1 on TBICDS.PATIENT_DEMOGRAPHICS (POSTAL_CODE);

prompt
prompt Creating table PATIENT_EMERGENCY_CONTACT
prompt ========================================
prompt
create table TBICDS.PATIENT_EMERGENCY_CONTACT
(
  PATIENT_ID      VARCHAR2(50) not null,
  NAME            VARCHAR2(80),
  RELATIONSHIP_ID NUMBER(11) default 0,
  ADDRESS1        VARCHAR2(80),
  ADDRESS2        VARCHAR2(80),
  CITY            VARCHAR2(50),
  POSTAL_CODE     VARCHAR2(50),
  HOMEPHONE       VARCHAR2(20),
  WORKPHONE       VARCHAR2(20),
  EMAIL           VARCHAR2(60),
  STATE_ID        NUMBER(11) default 0,
  LAST_UPDATED    DATE,
  LAST_UPDATED_BY NUMBER
)
;
comment on table TBICDS.PATIENT_EMERGENCY_CONTACT
  is 'Contains patient emergency contact information';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.PATIENT_ID
  is 'Patient ID (pk)';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.NAME
  is 'Emergency contact name';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.RELATIONSHIP_ID
  is 'Emergency contact relationship (fk)';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.ADDRESS1
  is 'Emergency contact address1';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.ADDRESS2
  is 'Emergency contact address2';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.CITY
  is 'Emergency contact city';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.POSTAL_CODE
  is 'Emergency contact postal code';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.HOMEPHONE
  is 'Emergency contact home phone';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.WORKPHONE
  is 'Emergency contact work phone';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.EMAIL
  is 'Emergency contact email';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.STATE_ID
  is 'Emergency contact state ID (fk)';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.LAST_UPDATED
  is 'Emergency contact last updated date/time';
comment on column TBICDS.PATIENT_EMERGENCY_CONTACT.LAST_UPDATED_BY
  is 'Emergency contact last updated by';
alter table TBICDS.PATIENT_EMERGENCY_CONTACT
  add constraint PK_PATIENT_EMERGENCY_CONTACT primary key (PATIENT_ID);
create index TBICDS.POSTAL_CODE_2 on TBICDS.PATIENT_EMERGENCY_CONTACT (POSTAL_CODE);
create index TBICDS.RELATIONSHIP_ID on TBICDS.PATIENT_EMERGENCY_CONTACT (RELATIONSHIP_ID);

prompt
prompt Creating table PATIENT_ETHNICITY
prompt ================================
prompt
create table TBICDS.PATIENT_ETHNICITY
(
  PATIENT_ID   VARCHAR2(50) not null,
  ETHNICITY_ID NUMBER(2) not null
)
;
comment on table TBICDS.PATIENT_ETHNICITY
  is 'Contains patient ethnicity information.';
comment on column TBICDS.PATIENT_ETHNICITY.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.PATIENT_ETHNICITY.ETHNICITY_ID
  is 'Ethnicity ID (fk)';
alter table TBICDS.PATIENT_ETHNICITY
  add constraint PATIENT_ETHNICITY_KEY_PK primary key (PATIENT_ID);
alter table TBICDS.PATIENT_ETHNICITY
  add constraint PATIENT_ETHNICITY_KEY_FK01 foreign key (PATIENT_ID)
  references TBICDS.PATIENT_DEMOGRAPHICS (PATIENT_ID);

prompt
prompt Creating table PATIENT_MEDICAL_HX
prompt =================================
prompt
create table TBICDS.PATIENT_MEDICAL_HX
(
  PATIENT_ID      VARCHAR2(50) not null,
  REGION_ID       NUMBER,
  SITE_ID         NUMBER,
  PAT_PW_ID       NUMBER,
  PAT_PW_EVENT_ID NUMBER,
  MED_HX_DATE     DATE,
  FX_USER_ID      NUMBER
)
;
comment on table TBICDS.PATIENT_MEDICAL_HX
  is 'Contains past medical history information';
comment on column TBICDS.PATIENT_MEDICAL_HX.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.PATIENT_MEDICAL_HX.REGION_ID
  is 'Region id  (fk)';
comment on column TBICDS.PATIENT_MEDICAL_HX.SITE_ID
  is 'Site id';
comment on column TBICDS.PATIENT_MEDICAL_HX.PAT_PW_ID
  is 'Patient pathway ID';
comment on column TBICDS.PATIENT_MEDICAL_HX.PAT_PW_EVENT_ID
  is 'Patient pathway event ID';
comment on column TBICDS.PATIENT_MEDICAL_HX.MED_HX_DATE
  is 'date/time medical history was updated';
comment on column TBICDS.PATIENT_MEDICAL_HX.FX_USER_ID
  is 'user id of the person that updated the medical history';

prompt
prompt Creating table PATIENT_RACE
prompt ===========================
prompt
create table TBICDS.PATIENT_RACE
(
  PATIENT_ID VARCHAR2(50) not null,
  RACE_ID    NUMBER(2) not null
)
;
comment on table TBICDS.PATIENT_RACE
  is 'Contains patient race information.';
comment on column TBICDS.PATIENT_RACE.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.PATIENT_RACE.RACE_ID
  is 'Race ID (fk)';
alter table TBICDS.PATIENT_RACE
  add constraint PATIENT_RACE_KEY_PK primary key (PATIENT_ID, RACE_ID);
alter table TBICDS.PATIENT_RACE
  add constraint PATIENT_RACE_KEY_FK01 foreign key (PATIENT_ID)
  references TBICDS.PATIENT_DEMOGRAPHICS (PATIENT_ID);

prompt
prompt Creating table PATIENT_SOCIOECONOMIC
prompt ====================================
prompt
create table TBICDS.PATIENT_SOCIOECONOMIC
(
  PATIENT_ID              VARCHAR2(50),
  HIGHEST_GRADE_ID        NUMBER,
  HIGHEST_DEGREE_ID       NUMBER,
  MARITAL_STATUS_ID       NUMBER,
  EMPLOYMENT_STATUS_ID    NUMBER,
  JOB_CLASSIFICATION_ID   NUMBER,
  LAST_MODIFIED           DATE,
  LAST_MODIFIED_BY        NUMBER,
  EMPLOYMENT_STATUS_OTHER VARCHAR2(128)
)
;
comment on table TBICDS.PATIENT_SOCIOECONOMIC
  is 'Contains patient socioeconomic information.';
comment on column TBICDS.PATIENT_SOCIOECONOMIC.PATIENT_ID
  is 'Patient Id (used in the application)';
comment on column TBICDS.PATIENT_SOCIOECONOMIC.HIGHEST_GRADE_ID
  is 'FK to STAT_DATA_COLLECTION table, _HIGHEST_GRADE subset (fk)';
comment on column TBICDS.PATIENT_SOCIOECONOMIC.HIGHEST_DEGREE_ID
  is 'FK to STAT_DATA_COLLECTION table, _HIGHEST_DEGREE subset (fk)';
comment on column TBICDS.PATIENT_SOCIOECONOMIC.MARITAL_STATUS_ID
  is 'FK to STAT_DATA_COLLECTION table, _MARITAL_STATUS subset (fk)';
comment on column TBICDS.PATIENT_SOCIOECONOMIC.EMPLOYMENT_STATUS_ID
  is 'FK to STAT_DATA_COLLECTION table, _EMPLOYMENT_STATUS subset (fk)';
comment on column TBICDS.PATIENT_SOCIOECONOMIC.JOB_CLASSIFICATION_ID
  is 'FK to STAT_DATA_COLLECTION table, _JOB_CLASSIFICATION subset (fk)';
comment on column TBICDS.PATIENT_SOCIOECONOMIC.LAST_MODIFIED
  is 'date and time when record was modified';
comment on column TBICDS.PATIENT_SOCIOECONOMIC.LAST_MODIFIED_BY
  is 'FX_USER_ID of the user who modified the record (fk)';
comment on column TBICDS.PATIENT_SOCIOECONOMIC.EMPLOYMENT_STATUS_OTHER
  is 'patient other employment status';
alter table TBICDS.PATIENT_SOCIOECONOMIC
  add constraint K_PATIENT_ID unique (PATIENT_ID);
alter table TBICDS.PATIENT_SOCIOECONOMIC
  add constraint FK_PAT_DEMO_PAT_SOCECONOMIC foreign key (PATIENT_ID)
  references TBICDS.PATIENT_DEMOGRAPHICS (PATIENT_ID) on delete cascade;

prompt
prompt Creating table PATIENT_VISIT
prompt ============================
prompt
create table TBICDS.PATIENT_VISIT
(
  REGION_ID           NUMBER,
  SITE_ID             NUMBER,
  DFN                 VARCHAR2(255),
  VISIT_ID            VARCHAR2(255),
  VISIT_LOCATION_ID   NUMBER,
  VISIT_LOCATION_NAME VARCHAR2(255),
  VISIT_TIMESTAMP     VARCHAR2(255),
  VISIT_STATUS        VARCHAR2(255),
  VISIT_TYPE          VARCHAR2(255),
  VISIT_DATETIME      DATE
)
;
comment on column TBICDS.PATIENT_VISIT.REGION_ID
  is 'region id';
comment on column TBICDS.PATIENT_VISIT.SITE_ID
  is 'site id';
comment on column TBICDS.PATIENT_VISIT.DFN
  is 'pat dfn';
comment on column TBICDS.PATIENT_VISIT.VISIT_ID
  is 'patient consult id';
comment on column TBICDS.PATIENT_VISIT.VISIT_LOCATION_ID
  is 'consult time stamp';
comment on column TBICDS.PATIENT_VISIT.VISIT_LOCATION_NAME
  is 'consult status';
comment on column TBICDS.PATIENT_VISIT.VISIT_TIMESTAMP
  is 'consult title';
comment on column TBICDS.PATIENT_VISIT.VISIT_STATUS
  is 'consult text';

prompt
prompt Creating table PAT_ETH_RACE_SOURCE
prompt ==================================
prompt
create table TBICDS.PAT_ETH_RACE_SOURCE
(
  PATIENT_ID         VARCHAR2(50) not null,
  ETH_RACE_SOURCE_ID NUMBER(2) not null
)
;
comment on table TBICDS.PAT_ETH_RACE_SOURCE
  is 'Contains patient ethnicity source information.';
comment on column TBICDS.PAT_ETH_RACE_SOURCE.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.PAT_ETH_RACE_SOURCE.ETH_RACE_SOURCE_ID
  is 'ethnicity race source ID (fk)';
alter table TBICDS.PAT_ETH_RACE_SOURCE
  add constraint PAT_ETH_RACE_SOURCE_KEY_PK primary key (PATIENT_ID);

prompt
prompt Creating table PAT_PW
prompt =====================
prompt
create table TBICDS.PAT_PW
(
  PATIENT_ID   VARCHAR2(50) not null,
  DATE_CREATED DATE,
  CREATED_BY   NUMBER,
  STATUS       NUMBER,
  PW_TYPE_ID   NUMBER,
  REGION_ID    NUMBER,
  SITE_ID      NUMBER,
  PAT_PW_ID    NUMBER,
  PW_TITLE     VARCHAR2(255),
  PW_DESCR     VARCHAR2(1024),
  CPA_ID       NUMBER,
  PW_ID        NUMBER
)
;
comment on table TBICDS.PAT_PW
  is 'Contains patient pathway information.';
comment on column TBICDS.PAT_PW.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.PAT_PW.DATE_CREATED
  is 'Date created';
comment on column TBICDS.PAT_PW.CREATED_BY
  is 'User id who created the pathway (fk)';
comment on column TBICDS.PAT_PW.STATUS
  is 'Pathway status 1 = open, 2 = closed, 3 = cancelled, 4 = deleted';
comment on column TBICDS.PAT_PW.PW_TYPE_ID
  is 'Type of pathway, inpat, outpat, open (fk)';
comment on column TBICDS.PAT_PW.REGION_ID
  is 'Region id (fk)';
comment on column TBICDS.PAT_PW.SITE_ID
  is 'Site id (fk)';
comment on column TBICDS.PAT_PW.PAT_PW_ID
  is 'Patient pathway ID (pk)';
comment on column TBICDS.PAT_PW.PW_TITLE
  is 'Title of the pathway';
comment on column TBICDS.PAT_PW.PW_DESCR
  is 'Description of the pathway';
comment on column TBICDS.PAT_PW.CPA_ID
  is 'Clinical program area';
comment on column TBICDS.PAT_PW.PW_ID
  is 'Pathway id';
alter table TBICDS.PAT_PW
  add constraint PAT_CPA_PW_FK1 foreign key (PATIENT_ID)
  references TBICDS.PATIENT_DEMOGRAPHICS (PATIENT_ID);

prompt
prompt Creating table PAT_PW_EVENT
prompt ===========================
prompt
create table TBICDS.PAT_PW_EVENT
(
  PATIENT_ID           VARCHAR2(50) not null,
  STATUS               NUMBER,
  DATE_SCHEDULED       DATE,
  DATE_STARTED         DATE,
  DATE_COMPLETED       DATE,
  REGION_ID            NUMBER,
  SITE_ID              NUMBER,
  PAT_PW_ID            NUMBER,
  EVENT_TITLE          VARCHAR2(255),
  EVENT_DESCR          VARCHAR2(1024),
  SORT_ORDER           NUMBER,
  EVENT_FREQUENCY      NUMBER,
  EVENT_RECURRENT      NUMBER,
  PW_EVENT_TYPE_ID     NUMBER,
  PAT_PW_EVENT_ID      NUMBER,
  MERGED               NUMBER,
  DATE_SIGNED          DATE,
  SIGNED_BY            NUMBER,
  PLAN_PAT_PW_EVENT_ID NUMBER,
  PLAN_TEXT            CLOB,
  NOTE_TEXT            CLOB,
  TIU_DFN              VARCHAR2(100),
  TIU_DUZ              VARCHAR2(100),
  TIU_ENCOUNTER_ID     VARCHAR2(100),
  TIU_CONSULT_IEN      VARCHAR2(100),
  TIU_COSIGNER_DUZ     VARCHAR2(100),
  TIU_NOTE_TITLE_IEN   VARCHAR2(100),
  TIU_NOTE             CLOB,
  TIU_CLINIC_ID        NUMBER,
  TIU_DATE_SUBMITTED   DATE,
  TIU_ENCOUNTER_TYPE   NUMBER,
  TIU_NOTE_TITLE       VARCHAR2(255),
  TIU_LOCATION         VARCHAR2(255),
  TIU_COSIGNER         VARCHAR2(255),
  TIU_NOTE_ID          VARCHAR2(100),
  TIU_CONSULT          VARCHAR2(255),
  CREATED_BY           NUMBER
)
;
comment on table TBICDS.PAT_PW_EVENT
  is 'Contains patient pathway event information.';
comment on column TBICDS.PAT_PW_EVENT.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.PAT_PW_EVENT.STATUS
  is 'Event status: 0 = scheduled, 1=in progress, 2=complete, 3=deleted, 4=rescheduled';
comment on column TBICDS.PAT_PW_EVENT.DATE_SCHEDULED
  is 'Date event is scheduled to happen';
comment on column TBICDS.PAT_PW_EVENT.DATE_STARTED
  is 'Date event started';
comment on column TBICDS.PAT_PW_EVENT.DATE_COMPLETED
  is 'Date event completed';
comment on column TBICDS.PAT_PW_EVENT.REGION_ID
  is 'Region id  (fk)';
comment on column TBICDS.PAT_PW_EVENT.SITE_ID
  is 'Site id';
comment on column TBICDS.PAT_PW_EVENT.PAT_PW_ID
  is 'Unique instance of this pathway';
comment on column TBICDS.PAT_PW_EVENT.EVENT_TITLE
  is 'Pathway event title';
comment on column TBICDS.PAT_PW_EVENT.EVENT_DESCR
  is 'Pathway event descr';
comment on column TBICDS.PAT_PW_EVENT.SORT_ORDER
  is 'Pathway event sort order';
comment on column TBICDS.PAT_PW_EVENT.EVENT_FREQUENCY
  is 'Pathway event frequency';
comment on column TBICDS.PAT_PW_EVENT.EVENT_RECURRENT
  is 'Is the event recurrent, 0 = no, 1=yes';
comment on column TBICDS.PAT_PW_EVENT.PW_EVENT_TYPE_ID
  is 'Pathway event type ID: 1=scheduled, 2=out of cycle';
comment on column TBICDS.PAT_PW_EVENT.PAT_PW_EVENT_ID
  is 'Pathway event ID';
comment on column TBICDS.PAT_PW_EVENT.MERGED
  is 'N/A Identifies this event as the master event, used during the merge feature';
comment on column TBICDS.PAT_PW_EVENT.DATE_SIGNED
  is 'Date time pathway event was signed';
comment on column TBICDS.PAT_PW_EVENT.SIGNED_BY
  is 'User ID who signed the event';
comment on column TBICDS.PAT_PW_EVENT.PLAN_PAT_PW_EVENT_ID
  is 'patient pathway event id of the event used as the plan for this event';
comment on column TBICDS.PAT_PW_EVENT.PLAN_TEXT
  is 'full text of the plan for this event';
comment on column TBICDS.PAT_PW_EVENT.NOTE_TEXT
  is 'full text of the tiu note';
comment on column TBICDS.PAT_PW_EVENT.TIU_DFN
  is 'patient dfn used to write the tiu note';
comment on column TBICDS.PAT_PW_EVENT.TIU_DUZ
  is 'user duz who wrote the tiu note';
comment on column TBICDS.PAT_PW_EVENT.TIU_ENCOUNTER_ID
  is 'encounter id used to write the tiu note';
comment on column TBICDS.PAT_PW_EVENT.TIU_CONSULT_IEN
  is 'consult ien used to write the tiu note';
comment on column TBICDS.PAT_PW_EVENT.TIU_COSIGNER_DUZ
  is 'cosigner used to write the tiu note';
comment on column TBICDS.PAT_PW_EVENT.TIU_NOTE_TITLE_IEN
  is 'note title ien used to write the tiu note';
comment on column TBICDS.PAT_PW_EVENT.TIU_NOTE
  is 'actual tiu note successfully submitted';
comment on column TBICDS.PAT_PW_EVENT.TIU_CLINIC_ID
  is 'clinic id used to write the note';
comment on column TBICDS.PAT_PW_EVENT.TIU_DATE_SUBMITTED
  is 'date note successfully submitted to tiu';
comment on column TBICDS.PAT_PW_EVENT.TIU_ENCOUNTER_TYPE
  is '1 = admission, 2 = visit';
comment on column TBICDS.PAT_PW_EVENT.TIU_NOTE_TITLE
  is 'note title with ien';
comment on column TBICDS.PAT_PW_EVENT.TIU_LOCATION
  is 'location with encounter info';
comment on column TBICDS.PAT_PW_EVENT.TIU_COSIGNER
  is 'cosigner with ien';
comment on column TBICDS.PAT_PW_EVENT.TIU_NOTE_ID
  is 'tiu note id';
comment on column TBICDS.PAT_PW_EVENT.TIU_CONSULT
  is 'consult with ien';
comment on column TBICDS.PAT_PW_EVENT.CREATED_BY
  is 'User id who created the event (fk)';
alter table TBICDS.PAT_PW_EVENT
  add constraint PAT_CPA_PW_EVENT_FK1 foreign key (PATIENT_ID)
  references TBICDS.PATIENT_DEMOGRAPHICS (PATIENT_ID);

prompt
prompt Creating table PAT_PW_EVENT_ENTRY
prompt =================================
prompt
create table TBICDS.PAT_PW_EVENT_ENTRY
(
  PAT_PW_EVENT_ENTRY_ID NUMBER,
  PATIENT_ID            VARCHAR2(50) not null,
  PAT_PW_ID             NUMBER,
  PAT_PW_EVENT_ID       NUMBER,
  EVENT_ENTRY_TYPE_ID   NUMBER,
  EVENT_COMMENT         VARCHAR2(4000),
  FX_USER_ID            NUMBER,
  EVENT_DATE            DATE,
  EVENT_STATUS_ID       NUMBER default 0,
  PW_EVENT_MODULE_ID    NUMBER,
  EVENT_SEVERITY_ID     NUMBER default 0
)
;
comment on table TBICDS.PAT_PW_EVENT_ENTRY
  is 'Contains patient pathway event entry information.';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.PAT_PW_EVENT_ENTRY_ID
  is 'Event entry ID (pk)';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.PAT_PW_ID
  is 'Patient pathway ID (fk)';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.PAT_PW_EVENT_ID
  is 'Pathway event ID (fk)';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.EVENT_ENTRY_TYPE_ID
  is 'Event entry type id (fk)';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.EVENT_COMMENT
  is 'Event comment';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.FX_USER_ID
  is 'User ID who made the event comment';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.EVENT_DATE
  is 'Date time the event comment was made';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.EVENT_STATUS_ID
  is 'Event entry status ID (fk): better, same worse etc...';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.PW_EVENT_MODULE_ID
  is 'Event module ID (fk)';
comment on column TBICDS.PAT_PW_EVENT_ENTRY.EVENT_SEVERITY_ID
  is 'Event severity id (fk): unk,mild,moderate,severe';

prompt
prompt Creating table PAT_PW_EVENT_MODULE
prompt ==================================
prompt
create table TBICDS.PAT_PW_EVENT_MODULE
(
  PATIENT_ID         VARCHAR2(50) not null,
  MID                NUMBER,
  STATUS             NUMBER,
  REGION_ID          NUMBER,
  SITE_ID            NUMBER,
  DATE_STARTED       DATE,
  DATE_COMPLETED     DATE,
  PAT_PW_ID          NUMBER,
  INTAKE_ID          NUMBER,
  TIME_WINDOW        NUMBER,
  MODULE_FOR         NUMBER,
  SORT_ORDER         NUMBER,
  PAT_PW_EVENT_ID    NUMBER,
  DATE_SCHEDULED     DATE,
  MERGED             NUMBER default 0,
  PW_EVENT_MODULE_ID NUMBER,
  COMPLETED_BY       NUMBER
)
;
comment on table TBICDS.PAT_PW_EVENT_MODULE
  is 'Contains patient pathway event module information.';
comment on column TBICDS.PAT_PW_EVENT_MODULE.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.PAT_PW_EVENT_MODULE.MID
  is 'Module ID ';
comment on column TBICDS.PAT_PW_EVENT_MODULE.STATUS
  is 'Module Status: 0 = waiting, 1=complete, 2=cancelled, 3=deleted, 4=rescheduled';
comment on column TBICDS.PAT_PW_EVENT_MODULE.REGION_ID
  is 'Region id (fk)';
comment on column TBICDS.PAT_PW_EVENT_MODULE.SITE_ID
  is 'Site id (fk)';
comment on column TBICDS.PAT_PW_EVENT_MODULE.DATE_STARTED
  is 'Date event started';
comment on column TBICDS.PAT_PW_EVENT_MODULE.DATE_COMPLETED
  is 'Date event completed';
comment on column TBICDS.PAT_PW_EVENT_MODULE.PAT_PW_ID
  is 'Patient pathway ID ';
comment on column TBICDS.PAT_PW_EVENT_MODULE.INTAKE_ID
  is 'Intake ID (fk)';
comment on column TBICDS.PAT_PW_EVENT_MODULE.TIME_WINDOW
  is 'Window of time result is valid in hours';
comment on column TBICDS.PAT_PW_EVENT_MODULE.MODULE_FOR
  is 'Who completes the module: 1=provider, 2=patient, 3=both';
comment on column TBICDS.PAT_PW_EVENT_MODULE.SORT_ORDER
  is 'Sort order for display';
comment on column TBICDS.PAT_PW_EVENT_MODULE.PAT_PW_EVENT_ID
  is 'Patient pathway event ID ';
comment on column TBICDS.PAT_PW_EVENT_MODULE.DATE_SCHEDULED
  is 'Date Scheduled';
comment on column TBICDS.PAT_PW_EVENT_MODULE.MERGED
  is 'N/A 1= ignore';
comment on column TBICDS.PAT_PW_EVENT_MODULE.PW_EVENT_MODULE_ID
  is 'Uniquely identifies a pathway event module (pk)';
comment on column TBICDS.PAT_PW_EVENT_MODULE.COMPLETED_BY
  is 'last person to submit the instrument';
alter table TBICDS.PAT_PW_EVENT_MODULE
  add constraint PAT_CPA_PW_EVMOD_FK1 foreign key (PATIENT_ID)
  references TBICDS.PATIENT_DEMOGRAPHICS (PATIENT_ID);

prompt
prompt Creating table PAT_TREATMENT
prompt ============================
prompt
create table TBICDS.PAT_TREATMENT
(
  PATIENT_ID        VARCHAR2(50) not null,
  TREATMENT_ID      NUMBER not null,
  TREATMENT_TYPE_ID NUMBER not null,
  INITIAL_DATE      DATE,
  END_DATE          DATE,
  TREATMENT_TITLE   VARCHAR2(255),
  REGION_ID         NUMBER,
  SITE_ID           NUMBER
)
;
comment on table TBICDS.PAT_TREATMENT
  is 'Contains information related to a patients treatment';
comment on column TBICDS.PAT_TREATMENT.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.PAT_TREATMENT.TREATMENT_ID
  is 'uniquie treatment id (pk)';
comment on column TBICDS.PAT_TREATMENT.TREATMENT_TYPE_ID
  is '1=outpatient, 2=inpatient';
comment on column TBICDS.PAT_TREATMENT.INITIAL_DATE
  is 'Initial date';
comment on column TBICDS.PAT_TREATMENT.END_DATE
  is 'End date';
comment on column TBICDS.PAT_TREATMENT.TREATMENT_TITLE
  is 'title of the treatment';
comment on column TBICDS.PAT_TREATMENT.REGION_ID
  is 'Region id (fk)';
comment on column TBICDS.PAT_TREATMENT.SITE_ID
  is 'Site id (fk)';

prompt
prompt Creating table PAT_TREATMENT_PROGRAM
prompt ====================================
prompt
create table TBICDS.PAT_TREATMENT_PROGRAM
(
  PATIENT_ID   VARCHAR2(50) not null,
  TREATMENT_ID NUMBER not null,
  CPA_ID       NUMBER,
  REGION_ID    NUMBER,
  SITE_ID      NUMBER,
  INITIAL_DATE DATE,
  END_DATE     DATE,
  PROGRAM_ID   NUMBER
)
;
comment on table TBICDS.PAT_TREATMENT_PROGRAM
  is 'Contains information related to a patients treatment program';
comment on column TBICDS.PAT_TREATMENT_PROGRAM.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.PAT_TREATMENT_PROGRAM.TREATMENT_ID
  is 'treatment id (fk)';
comment on column TBICDS.PAT_TREATMENT_PROGRAM.CPA_ID
  is 'Clinical program area ID (fk)';
comment on column TBICDS.PAT_TREATMENT_PROGRAM.REGION_ID
  is 'Region ID (fk)';
comment on column TBICDS.PAT_TREATMENT_PROGRAM.SITE_ID
  is 'Site ID (fk)';
comment on column TBICDS.PAT_TREATMENT_PROGRAM.INITIAL_DATE
  is 'Initial date';
comment on column TBICDS.PAT_TREATMENT_PROGRAM.END_DATE
  is 'End date';
comment on column TBICDS.PAT_TREATMENT_PROGRAM.PROGRAM_ID
  is 'unique program id (pk)';

prompt
prompt Creating table PLAN_TABLE
prompt =========================
prompt
create table TBICDS.PLAN_TABLE
(
  STATEMENT_ID      VARCHAR2(30),
  PLAN_ID           NUMBER,
  TIMESTAMP         DATE,
  REMARKS           VARCHAR2(4000),
  OPERATION         VARCHAR2(30),
  OPTIONS           VARCHAR2(255),
  OBJECT_NODE       VARCHAR2(128),
  OBJECT_OWNER      VARCHAR2(30),
  OBJECT_NAME       VARCHAR2(30),
  OBJECT_ALIAS      VARCHAR2(65),
  OBJECT_INSTANCE   INTEGER,
  OBJECT_TYPE       VARCHAR2(30),
  OPTIMIZER         VARCHAR2(255),
  SEARCH_COLUMNS    NUMBER,
  ID                INTEGER,
  PARENT_ID         INTEGER,
  DEPTH             INTEGER,
  POSITION          INTEGER,
  COST              INTEGER,
  CARDINALITY       INTEGER,
  BYTES             INTEGER,
  OTHER_TAG         VARCHAR2(255),
  PARTITION_START   VARCHAR2(255),
  PARTITION_STOP    VARCHAR2(255),
  PARTITION_ID      INTEGER,
  OTHER             CLOB default '',
  DISTRIBUTION      VARCHAR2(30),
  CPU_COST          INTEGER,
  IO_COST           INTEGER,
  TEMP_SPACE        INTEGER,
  ACCESS_PREDICATES VARCHAR2(4000),
  FILTER_PREDICATES VARCHAR2(4000),
  PROJECTION        VARCHAR2(4000),
  TIME              INTEGER,
  QBLOCK_NAME       VARCHAR2(30)
)
;

prompt
prompt Creating table REPORT_POPULATION
prompt ================================
prompt
create table TBICDS.REPORT_POPULATION
(
  PATIENT_ID   VARCHAR2(50) not null,
  FX_USER_ID   NUMBER not null,
  INITIAL_DATE DATE,
  END_DATE     DATE,
  SITE_ID      NUMBER
)
;
comment on column TBICDS.REPORT_POPULATION.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.REPORT_POPULATION.FX_USER_ID
  is 'Unique User ID links to the app_user table (pk)';
comment on column TBICDS.REPORT_POPULATION.INITIAL_DATE
  is 'initial date of the treatment/program';
comment on column TBICDS.REPORT_POPULATION.END_DATE
  is 'end date of the treatment/program';
comment on column TBICDS.REPORT_POPULATION.SITE_ID
  is 'Site ID (pk)';

prompt
prompt Creating table REPORT_POPULATION_MODULE
prompt =======================================
prompt
create table TBICDS.REPORT_POPULATION_MODULE
(
  PATIENT_ID          VARCHAR2(50) not null,
  FX_USER_ID          NUMBER not null,
  INITIAL_DATE        DATE,
  END_DATE            DATE,
  MID                 NUMBER,
  ADMISSION_INTAKE_ID NUMBER,
  DISCHARGE_INTAKE_ID NUMBER,
  FOLLOWUP_INTAKE_ID  NUMBER,
  LOS                 NUMBER,
  SITE_ID             NUMBER
)
;
comment on column TBICDS.REPORT_POPULATION_MODULE.PATIENT_ID
  is 'Patient ID (fk)';
comment on column TBICDS.REPORT_POPULATION_MODULE.FX_USER_ID
  is 'Unique User ID links to the app_user table (pk)';
comment on column TBICDS.REPORT_POPULATION_MODULE.INITIAL_DATE
  is 'initial date of the treatment/program';
comment on column TBICDS.REPORT_POPULATION_MODULE.END_DATE
  is 'end date of the treatment/program';
comment on column TBICDS.REPORT_POPULATION_MODULE.MID
  is 'MID of report clicked after initial load of table';
comment on column TBICDS.REPORT_POPULATION_MODULE.ADMISSION_INTAKE_ID
  is 'data_intake intake id of the admission instrument';
comment on column TBICDS.REPORT_POPULATION_MODULE.DISCHARGE_INTAKE_ID
  is 'data_intake intake id of the discharge instrument';
comment on column TBICDS.REPORT_POPULATION_MODULE.FOLLOWUP_INTAKE_ID
  is 'data_intake intake_id of the followup instrument';
comment on column TBICDS.REPORT_POPULATION_MODULE.LOS
  is 'length of stay';
comment on column TBICDS.REPORT_POPULATION_MODULE.SITE_ID
  is 'site id';

prompt
prompt Creating table STAT_DATA_COLLECTION
prompt ===================================
prompt
create table TBICDS.STAT_DATA_COLLECTION
(
  COLLECTION_TYPE    VARCHAR2(255) not null,
  COLLECTION_ITEM_ID NUMBER not null,
  ITEM               VARCHAR2(80),
  ITEM_TYPE          VARCHAR2(10),
  ALTERNATE_LANGUAGE VARCHAR2(255),
  PLACEHOLDER2       VARCHAR2(10),
  PLACEHOLDER3       VARCHAR2(10),
  PLACEHOLDER4       VARCHAR2(10),
  ACTIVE             NUMBER default 1,
  LANGUAGE_ID        NUMBER default 1
)
;
comment on table TBICDS.STAT_DATA_COLLECTION
  is 'Contains static data used throughout the application.';
comment on column TBICDS.STAT_DATA_COLLECTION.COLLECTION_TYPE
  is 'Descriptive name where the data will vbe used e.g. _ALLERGY (allways preceed with an underscore)';
comment on column TBICDS.STAT_DATA_COLLECTION.COLLECTION_ITEM_ID
  is 'Collection enumeration';
comment on column TBICDS.STAT_DATA_COLLECTION.ITEM
  is 'Actual Item data';
comment on column TBICDS.STAT_DATA_COLLECTION.ITEM_TYPE
  is 'Item type: string, number';
comment on column TBICDS.STAT_DATA_COLLECTION.ALTERNATE_LANGUAGE
  is 'Alternate language of the item';
comment on column TBICDS.STAT_DATA_COLLECTION.PLACEHOLDER2
  is 'N/A';
comment on column TBICDS.STAT_DATA_COLLECTION.PLACEHOLDER3
  is 'N/A';
comment on column TBICDS.STAT_DATA_COLLECTION.PLACEHOLDER4
  is 'N/A';
comment on column TBICDS.STAT_DATA_COLLECTION.ACTIVE
  is 'Is this item active';
comment on column TBICDS.STAT_DATA_COLLECTION.LANGUAGE_ID
  is 'Language ID: 1=English; 2=Spanish';
alter table TBICDS.STAT_DATA_COLLECTION
  add constraint STAT_DATA_COLLECTION_PK primary key (COLLECTION_TYPE, COLLECTION_ITEM_ID);
create index TBICDS.STAT_DATA_COLLECTION_NDX01 on TBICDS.STAT_DATA_COLLECTION (COLLECTION_TYPE);
create index TBICDS.STAT_DATA_COLLECTION_NDX02 on TBICDS.STAT_DATA_COLLECTION (COLLECTION_ITEM_ID);

prompt
prompt Creating table STAT_EVENT_ENTRY_TYPE
prompt ====================================
prompt
create table TBICDS.STAT_EVENT_ENTRY_TYPE
(
  EVENT_ENTRY_TYPE_ID NUMBER,
  EVENT_ENTRY_TYPE    VARCHAR2(255),
  SORT_ORDER          NUMBER
)
;
comment on column TBICDS.STAT_EVENT_ENTRY_TYPE.EVENT_ENTRY_TYPE_ID
  is 'Event entry type ID (pk)';
comment on column TBICDS.STAT_EVENT_ENTRY_TYPE.EVENT_ENTRY_TYPE
  is 'Event entry type';
comment on column TBICDS.STAT_EVENT_ENTRY_TYPE.SORT_ORDER
  is 'Sort order for display';

prompt
prompt Creating table STAT_EVENT_SEVERITY
prompt ==================================
prompt
create table TBICDS.STAT_EVENT_SEVERITY
(
  EVENT_SEVERITY_ID NUMBER,
  EVENT_SEVERITY    VARCHAR2(255),
  SORT_ORDER        NUMBER
)
;
comment on column TBICDS.STAT_EVENT_SEVERITY.EVENT_SEVERITY_ID
  is 'Event severity ID (pk)';
comment on column TBICDS.STAT_EVENT_SEVERITY.EVENT_SEVERITY
  is 'Event severity';
comment on column TBICDS.STAT_EVENT_SEVERITY.SORT_ORDER
  is 'Sort order for display';

prompt
prompt Creating table STAT_EVENT_STATUS
prompt ================================
prompt
create table TBICDS.STAT_EVENT_STATUS
(
  EVENT_STATUS_ID NUMBER,
  EVENT_STATUS    VARCHAR2(255),
  SORT_ORDER      NUMBER
)
;
comment on column TBICDS.STAT_EVENT_STATUS.EVENT_STATUS_ID
  is 'Event status ID (pk)';
comment on column TBICDS.STAT_EVENT_STATUS.EVENT_STATUS
  is 'Event status';
comment on column TBICDS.STAT_EVENT_STATUS.SORT_ORDER
  is 'Sort order for display';

prompt
prompt Creating table STAT_MENU_ITEMS
prompt ==============================
prompt
create table TBICDS.STAT_MENU_ITEMS
(
  MENU_ITEM_ID        NUMBER(11),
  MENU_ITEM           VARCHAR2(255),
  HAS_CHILDREN        NUMBER(2) default 0,
  HAS_PARENT          NUMBER(2) default 0,
  PARENT_ID           NUMBER(11) default 0,
  HREF                VARCHAR2(255),
  HTML_PROPERTY       VARCHAR2(255),
  JS_PROPERTY         VARCHAR2(255),
  USER_TYPE           NUMBER(12),
  USER_RIGHT          NUMBER(12) default 0,
  IS_LOGGED_IN        NUMBER(2) default 1,
  SELECTED_PATIENT    NUMBER(2) default 0,
  SELECTED_ENCOUNTER  NUMBER(2) default 0,
  ACTIVE              NUMBER(2) default 1,
  ITEM_TYPE           NUMBER(2) default 1,
  TITLE               VARCHAR2(255),
  WIDTH               NUMBER default 32,
  HEIGHT              NUMBER default 32,
  IMG_SRC             VARCHAR2(255),
  HAS_OPEN_CASE       NUMBER(2) default 0,
  TOOLBAR_SORT_ORDER  NUMBER,
  ICON_PROPERTY       VARCHAR2(255),
  REQ_READWRITE_RIGHT NUMBER(12) default 0,
  CHECK_PAT_LOCK      NUMBER(1) default 0,
  MENU_SORT_ORDER     NUMBER,
  CLOSES_PATIENT      NUMBER default 0,
  IGNORE_ON_TIU       NUMBER default 0
)
;
comment on column TBICDS.STAT_MENU_ITEMS.CHECK_PAT_LOCK
  is '0 do not check for patient record lock status, 1 check...';

prompt
prompt Creating table STAT_SEC_QUESTIONS
prompt =================================
prompt
create table TBICDS.STAT_SEC_QUESTIONS
(
  QUESTION_ID    NUMBER,
  QUESTION       VARCHAR2(255),
  QUESTION_GROUP NUMBER,
  ACTIVE         NUMBER default 1
)
;

prompt
prompt Creating table STAT_USER_RIGHTS
prompt ===============================
prompt
create table TBICDS.STAT_USER_RIGHTS
(
  STAT_RIGHT_ID NUMBER(5) default 0 not null,
  RIGHT_DESC    VARCHAR2(255),
  RIGHT_BIN     VARCHAR2(32),
  RIGHT_HEX     VARCHAR2(32),
  RIGHT_DEC     NUMBER(12),
  ACTIVE        NUMBER(2) default 1,
  VISIBLE       NUMBER(2) default 1,
  COMMENTS      VARCHAR2(255),
  SORT_ORDER    NUMBER,
  HAS_MODE      NUMBER(2) default 1
)
;
comment on table TBICDS.STAT_USER_RIGHTS
  is 'Contains information related to user rights';
comment on column TBICDS.STAT_USER_RIGHTS.STAT_RIGHT_ID
  is 'Right ID (pk)';
comment on column TBICDS.STAT_USER_RIGHTS.RIGHT_DESC
  is 'Right description';
comment on column TBICDS.STAT_USER_RIGHTS.RIGHT_BIN
  is 'Right binary representation';
comment on column TBICDS.STAT_USER_RIGHTS.RIGHT_HEX
  is 'Right HEX representation';
comment on column TBICDS.STAT_USER_RIGHTS.RIGHT_DEC
  is 'Right decimal representation';
comment on column TBICDS.STAT_USER_RIGHTS.ACTIVE
  is 'Is this right active';
comment on column TBICDS.STAT_USER_RIGHTS.VISIBLE
  is 'Is this right visible';
comment on column TBICDS.STAT_USER_RIGHTS.COMMENTS
  is 'Right comments';
comment on column TBICDS.STAT_USER_RIGHTS.SORT_ORDER
  is 'Sort order for display';
comment on column TBICDS.STAT_USER_RIGHTS.HAS_MODE
  is 'Has mode 1: If the rights use Read Only modes; 0: Modes does not apply to this right';
alter table TBICDS.STAT_USER_RIGHTS
  add constraint PK_STAT_USER_RIGHTS primary key (STAT_RIGHT_ID);

prompt
prompt Creating table STAT_USER_TYPES
prompt ==============================
prompt
create table TBICDS.STAT_USER_TYPES
(
  STAT_USERTYPE_ID NUMBER(11) not null,
  USERTYPE_DESC    VARCHAR2(255) not null,
  ACTIVE           NUMBER(2) default 1,
  VISIBLE          NUMBER(2) default 1,
  COMMENTS         VARCHAR2(255)
)
;
comment on table TBICDS.STAT_USER_TYPES
  is 'Contains information related to user types';
comment on column TBICDS.STAT_USER_TYPES.STAT_USERTYPE_ID
  is 'User type ID (pk)';
comment on column TBICDS.STAT_USER_TYPES.USERTYPE_DESC
  is 'User type description';
comment on column TBICDS.STAT_USER_TYPES.ACTIVE
  is 'Is this type active';
comment on column TBICDS.STAT_USER_TYPES.VISIBLE
  is 'Is this type visible';
comment on column TBICDS.STAT_USER_TYPES.COMMENTS
  is 'User type comments';

prompt
prompt Creating table TEMPLATE
prompt =======================
prompt
create table TBICDS.TEMPLATE
(
  TEMPLATE_ID       INTEGER not null,
  TYPE_ID           INTEGER,
  DESCRIPTION       VARCHAR2(80),
  CREATOR_ID        VARCHAR2(50),
  CREATED_DATE      DATE,
  ACTIVE            INTEGER,
  TEMPLATE_GROUP_ID NUMBER,
  TEMPLATE          CLOB,
  READ_ONLY         NUMBER default 0
)
;
comment on table TBICDS.TEMPLATE
  is 'Contains information related to templates';
comment on column TBICDS.TEMPLATE.TEMPLATE_ID
  is 'Template ID (pk)';
comment on column TBICDS.TEMPLATE.TYPE_ID
  is 'Type ID (fk)';
comment on column TBICDS.TEMPLATE.DESCRIPTION
  is 'Template description';
comment on column TBICDS.TEMPLATE.CREATOR_ID
  is 'Who created the template (fk)';
comment on column TBICDS.TEMPLATE.CREATED_DATE
  is 'Date template created';
comment on column TBICDS.TEMPLATE.ACTIVE
  is 'Is this template active';
comment on column TBICDS.TEMPLATE.TEMPLATE_GROUP_ID
  is 'Template group ID';
comment on column TBICDS.TEMPLATE.TEMPLATE
  is 'Template text';
comment on column TBICDS.TEMPLATE.READ_ONLY
  is 'Is this template read only';
alter table TBICDS.TEMPLATE
  add constraint PK_TEMPLATE_ID primary key (TEMPLATE_ID);

prompt
prompt Creating table TEMPLATE_GROUP
prompt =============================
prompt
create table TBICDS.TEMPLATE_GROUP
(
  TEMPLATE_GROUP_ID NUMBER,
  GROUP_NAME        VARCHAR2(255),
  COMMENTS          VARCHAR2(255),
  ACTIVE            NUMBER default 1,
  CREATED_BY        NUMBER,
  LAST_UPDATED      DATE,
  LAST_UPDATED_BY   NUMBER,
  READ_ONLY         NUMBER default 0
)
;
comment on table TBICDS.TEMPLATE_GROUP
  is 'Contains information related to template groups';
comment on column TBICDS.TEMPLATE_GROUP.TEMPLATE_GROUP_ID
  is 'Template group ID (pk)';
comment on column TBICDS.TEMPLATE_GROUP.GROUP_NAME
  is 'Group name';
comment on column TBICDS.TEMPLATE_GROUP.COMMENTS
  is 'Group comments';
comment on column TBICDS.TEMPLATE_GROUP.ACTIVE
  is 'Is this group active';
comment on column TBICDS.TEMPLATE_GROUP.CREATED_BY
  is 'Template group created by (fk)';
comment on column TBICDS.TEMPLATE_GROUP.LAST_UPDATED
  is 'Date group last updated';
comment on column TBICDS.TEMPLATE_GROUP.LAST_UPDATED_BY
  is 'Template group updated by (fk)';
comment on column TBICDS.TEMPLATE_GROUP.READ_ONLY
  is 'Is this template group read only.';

prompt
prompt Creating table TEMPLATE_ITEM
prompt ============================
prompt
create table TBICDS.TEMPLATE_ITEM
(
  DESCRIPTION       VARCHAR2(50) not null,
  ITEM_GROUP_ID     INTEGER,
  ITEM_SQL          VARCHAR2(4000),
  HELP_TEXT         VARCHAR2(4000),
  ACTIVE            INTEGER default 1,
  ITEM_ID           NUMBER,
  TEMPLATE_GROUP_ID NUMBER
)
;
comment on table TBICDS.TEMPLATE_ITEM
  is 'Contains information related to template items';
comment on column TBICDS.TEMPLATE_ITEM.DESCRIPTION
  is 'Template item description (pk)';
comment on column TBICDS.TEMPLATE_ITEM.ITEM_GROUP_ID
  is 'Template item group id';
comment on column TBICDS.TEMPLATE_ITEM.ITEM_SQL
  is 'Template item SQL';
comment on column TBICDS.TEMPLATE_ITEM.HELP_TEXT
  is 'Template item help text';
comment on column TBICDS.TEMPLATE_ITEM.ACTIVE
  is 'Is this template item active';
comment on column TBICDS.TEMPLATE_ITEM.ITEM_ID
  is 'Template item ID (fk)';
comment on column TBICDS.TEMPLATE_ITEM.TEMPLATE_GROUP_ID
  is 'Template item group id (fk)';
alter table TBICDS.TEMPLATE_ITEM
  add constraint PK_DESCRIPTION primary key (DESCRIPTION);

prompt
prompt Creating table TEMPLATE_ITEM_GROUP
prompt ==================================
prompt
create table TBICDS.TEMPLATE_ITEM_GROUP
(
  GROUP_ID    INTEGER not null,
  DESCRIPTION VARCHAR2(50),
  ACTIVE      INTEGER
)
;
comment on table TBICDS.TEMPLATE_ITEM_GROUP
  is 'Contains template item group information';
comment on column TBICDS.TEMPLATE_ITEM_GROUP.GROUP_ID
  is 'Template item group ID (pk)';
comment on column TBICDS.TEMPLATE_ITEM_GROUP.DESCRIPTION
  is 'Template item group description ';
comment on column TBICDS.TEMPLATE_ITEM_GROUP.ACTIVE
  is 'Is this template item group active';
alter table TBICDS.TEMPLATE_ITEM_GROUP
  add constraint PK_GROUP_ID primary key (GROUP_ID);

prompt
prompt Creating table TEMPLATE_TYPE
prompt ============================
prompt
create table TBICDS.TEMPLATE_TYPE
(
  TYPE_ID     INTEGER not null,
  DESCRIPTION VARCHAR2(80),
  ACTIVE      INTEGER
)
;
comment on table TBICDS.TEMPLATE_TYPE
  is 'Contains template item type information';
comment on column TBICDS.TEMPLATE_TYPE.TYPE_ID
  is 'Template type ID (pk)';
comment on column TBICDS.TEMPLATE_TYPE.DESCRIPTION
  is 'Template type description';
comment on column TBICDS.TEMPLATE_TYPE.ACTIVE
  is 'Is this template type active';
alter table TBICDS.TEMPLATE_TYPE
  add constraint PK_TYPE_ID primary key (TYPE_ID);

prompt
prompt Creating table UTL_CLINIC
prompt =========================
prompt
create table TBICDS.UTL_CLINIC
(
  CLINIC_ID      NUMBER not null,
  CLINIC_LABEL   VARCHAR2(4000),
  XFER_SYSTEM_ID NUMBER,
  XFER_DATE      DATE,
  REGION_ID      NUMBER not null,
  SITE_ID        NUMBER not null
)
;
comment on table TBICDS.UTL_CLINIC
  is 'Contains clinic information transferred from MDWS';
comment on column TBICDS.UTL_CLINIC.CLINIC_ID
  is 'MDWS clinic ID (pk)';
comment on column TBICDS.UTL_CLINIC.CLINIC_LABEL
  is 'MDWS clinic label';
comment on column TBICDS.UTL_CLINIC.XFER_SYSTEM_ID
  is 'Transfer system ID (MDWS)';
comment on column TBICDS.UTL_CLINIC.XFER_DATE
  is 'Date transferred';
comment on column TBICDS.UTL_CLINIC.REGION_ID
  is 'Region ID (pk)';
comment on column TBICDS.UTL_CLINIC.SITE_ID
  is 'Site ID (pk)';
alter table TBICDS.UTL_CLINIC
  add constraint PKUTLCLINIC primary key (REGION_ID, SITE_ID, CLINIC_ID);

prompt
prompt Creating table UTL_NOTE_TITLE
prompt =============================
prompt
create table TBICDS.UTL_NOTE_TITLE
(
  NOTE_TITLE_TAG   NUMBER,
  NOTE_TITLE_LABEL VARCHAR2(4000),
  XFER_SYSTEM_ID   NUMBER,
  XFER_DATE        DATE,
  REGION_ID        NUMBER,
  SITE_ID          NUMBER,
  IS_CONSULT       NUMBER default 0
)
;
comment on table TBICDS.UTL_NOTE_TITLE
  is 'Contains note title information transferred from MDWS';
comment on column TBICDS.UTL_NOTE_TITLE.NOTE_TITLE_TAG
  is 'Note title tag (pk)';
comment on column TBICDS.UTL_NOTE_TITLE.NOTE_TITLE_LABEL
  is 'Note title label (pk)';
comment on column TBICDS.UTL_NOTE_TITLE.XFER_SYSTEM_ID
  is 'Transfer system id (MDWS)';
comment on column TBICDS.UTL_NOTE_TITLE.XFER_DATE
  is 'Date of transfer';
comment on column TBICDS.UTL_NOTE_TITLE.REGION_ID
  is 'Region id (pk)';
comment on column TBICDS.UTL_NOTE_TITLE.SITE_ID
  is 'Site id (pk)';
comment on column TBICDS.UTL_NOTE_TITLE.IS_CONSULT
  is 'Is this note title a consult note title';

prompt
prompt Creating table UTL_PARAMETER
prompt ============================
prompt
create table TBICDS.UTL_PARAMETER
(
  PARAMETER_NAME  VARCHAR2(128) not null,
  PARAMETER_VALUE VARCHAR2(4000) not null
)
;
comment on table TBICDS.UTL_PARAMETER
  is 'Contains parameter values used throughout the application';
comment on column TBICDS.UTL_PARAMETER.PARAMETER_NAME
  is 'Name of the parameter';
comment on column TBICDS.UTL_PARAMETER.PARAMETER_VALUE
  is 'Value of the parameter';
alter table TBICDS.UTL_PARAMETER
  add constraint UTL_PARAMETER_KEY_PK primary key (PARAMETER_NAME);

prompt
prompt Creating sequence SEQCMSMENUID
prompt ==============================
prompt
create sequence TBICDS.SEQCMSMENUID
minvalue 1
maxvalue 999999
start with 231
increment by 1
cache 20;

prompt
prompt Creating sequence SEQCPAPDEVICE
prompt ===============================
prompt
create sequence TBICDS.SEQCPAPDEVICE
minvalue 1
maxvalue 999999999
start with 330
increment by 1
cache 20;

prompt
prompt Creating sequence SEQEXPSTATISTICALRPT
prompt ======================================
prompt
create sequence TBICDS.SEQEXPSTATISTICALRPT
minvalue 1
maxvalue 999999999
start with 341
increment by 1
cache 20;

prompt
prompt Creating sequence SEQFXUSERID
prompt =============================
prompt
create sequence TBICDS.SEQFXUSERID
minvalue 1
maxvalue 999999999
start with 4032
increment by 1
cache 20;

prompt
prompt Creating sequence SEQINACTIVEPAP
prompt ================================
prompt
create sequence TBICDS.SEQINACTIVEPAP
minvalue 1
maxvalue 9999999999
start with 1
increment by 1
cache 10;

prompt
prompt Creating sequence SEQINTAKEID
prompt =============================
prompt
create sequence TBICDS.SEQINTAKEID
minvalue 100
maxvalue 9999999999
start with 3360
increment by 1
cache 10;

prompt
prompt Creating sequence SEQMSGID
prompt ==========================
prompt
create sequence TBICDS.SEQMSGID
minvalue 1
maxvalue 9999999
start with 589
increment by 1
cache 20;

prompt
prompt Creating sequence SEQPATEVENTID
prompt ===============================
prompt
create sequence TBICDS.SEQPATEVENTID
minvalue 1
maxvalue 999999999999999999
start with 8838
increment by 1
cache 20;

prompt
prompt Creating sequence SEQPATPWENTRYID
prompt =================================
prompt
create sequence TBICDS.SEQPATPWENTRYID
minvalue 1
maxvalue 999999999
start with 821
increment by 1
cache 20;

prompt
prompt Creating sequence SEQPATPWEVENTID
prompt =================================
prompt
create sequence TBICDS.SEQPATPWEVENTID
minvalue 1
maxvalue 999999999
start with 31401
increment by 1
cache 20;

prompt
prompt Creating sequence SEQPATPWEVENTMODULEID
prompt =======================================
prompt
create sequence TBICDS.SEQPATPWEVENTMODULEID
minvalue 1
maxvalue 999999999
start with 11921
increment by 1
cache 20;

prompt
prompt Creating sequence SEQPATPWID
prompt ============================
prompt
create sequence TBICDS.SEQPATPWID
minvalue 1
maxvalue 999999999
start with 741
increment by 1
cache 20;

prompt
prompt Creating sequence SEQPROBLEMID
prompt ==============================
prompt
create sequence TBICDS.SEQPROBLEMID
minvalue 1
maxvalue 9999999999
start with 500
increment by 1
cache 20;

prompt
prompt Creating sequence SEQREFERRALID
prompt ===============================
prompt
create sequence TBICDS.SEQREFERRALID
minvalue 1
maxvalue 9999999999
start with 305
increment by 1
cache 20;

prompt
prompt Creating sequence SEQSTATICPAGEID
prompt =================================
prompt
create sequence TBICDS.SEQSTATICPAGEID
minvalue 1
maxvalue 999999
start with 271
increment by 1
cache 20;

prompt
prompt Creating sequence SEQTEMPLATEGRPID
prompt ==================================
prompt
create sequence TBICDS.SEQTEMPLATEGRPID
minvalue 1
maxvalue 999999
start with 121
increment by 1
cache 20;

prompt
prompt Creating sequence SEQTEMPLATEID
prompt ===============================
prompt
create sequence TBICDS.SEQTEMPLATEID
minvalue 1
maxvalue 999999999
start with 320
increment by 1
cache 20;

prompt
prompt Creating sequence SEQTXDIAGNOSISID
prompt ==================================
prompt
create sequence TBICDS.SEQTXDIAGNOSISID
minvalue 1
maxvalue 999999999
start with 10540
increment by 1
cache 20;

prompt
prompt Creating sequence SEQTXPROBCRITERIA
prompt ===================================
prompt
create sequence TBICDS.SEQTXPROBCRITERIA
minvalue 1
maxvalue 9999999999
start with 1041
increment by 1
cache 20;

prompt
prompt Creating sequence SEQTXPROBCRITERIADEF
prompt ======================================
prompt
create sequence TBICDS.SEQTXPROBCRITERIADEF
minvalue 1
maxvalue 9999999999
start with 903
increment by 1
cache 20;

prompt
prompt Creating sequence SEQTXPROBLEMID
prompt ================================
prompt
create sequence TBICDS.SEQTXPROBLEMID
minvalue 1
maxvalue 9999999999
start with 859
increment by 1
cache 20;

prompt
prompt Creating sequence SEQ_APP_USER_ID
prompt =================================
prompt
create sequence TBICDS.SEQ_APP_USER_ID
minvalue 1
maxvalue 9999999999999
start with 10861
increment by 1
cache 20;

prompt
prompt Creating sequence SEQ_ENCOUNTERID
prompt =================================
prompt
create sequence TBICDS.SEQ_ENCOUNTERID
minvalue 1
maxvalue 999999999999999999999999999
start with 11286
increment by 1
cache 20;

prompt
prompt Creating sequence SEQ_PATTREATMENTID
prompt ====================================
prompt
create sequence TBICDS.SEQ_PATTREATMENTID
minvalue 1
maxvalue 999999999
start with 201
increment by 1
cache 20;

prompt
prompt Creating sequence SEQ_PATTREATPROGID
prompt ====================================
prompt
create sequence TBICDS.SEQ_PATTREATPROGID
minvalue 1
maxvalue 999999999
start with 241
increment by 1
cache 20;

prompt
prompt Creating view VW_INTAKE
prompt =======================
prompt
create or replace view tbicds.vw_intake as
select (select t1.module
         from (select t1.module, t4.mid, t4.tid, t4.qid, t4.rid
                from intake_module t1,
                     (select t2.mid, min(t2.tid) tid from intake_topic t2 group by t2.mid) t2,
                     (select t3.mid, t3.tid, min(t3.qid) qid from intake_question t3 group by t3.mid, t3.tid) t3,
                     (select t4.mid, t4.tid, t4.qid, min(t4.rid) rid from intake_response t4 group by  t4.mid, t4.tid, t4.qid) t4
                where t1.mid = t2.mid
                  and t2.mid = t3.mid
                  and t2.tid = t3.tid
                  and t3.mid = t4.mid
                  and t3.tid = t4.tid
                  and t3.qid = t4.qid
                ) t1
       where t1.mid = t4.mid
        and t1.tid = t4.tid
        and t1.qid = t4.qid
        and t1.rid = t4.rid
       ) as module,

       (select t1.topic
         from (select t1.topic, t4.mid, t4.tid, t4.qid, t4.rid
                from intake_topic t1,
                     (select t3.mid, t3.tid, min(t3.qid) qid from intake_question t3 group by t3.mid, t3.tid) t3,
                     (select t4.mid, t4.tid, t4.qid, min(t4.rid) rid from intake_response t4 group by  t4.mid, t4.tid, t4.qid) t4
                where t1.mid = t3.mid
                  and t1.tid = t3.tid
                  and t3.mid = t4.mid
                  and t3.tid = t4.tid
                  and t3.qid = t4.qid
                ) t1
       where t1.mid = t4.mid
        and t1.tid = t4.tid
        and t1.qid = t4.qid
        and t1.rid = t4.rid
       ) as topic,
       (select t1.question
         from (select t1.question, t4.mid, t4.tid, t4.qid, t4.rid
                from intake_question t1,
                     (select t4.mid, t4.tid, t4.qid, min(t4.rid) rid from intake_response t4 group by  t4.mid, t4.tid, t4.qid) t4
                where t1.mid = t4.mid
                  and t1.tid = t4.tid
                  and t1.qid = t4.qid
                ) t1
       where t1.mid = t4.mid
        and t1.tid = t4.tid
        and t1.qid = t4.qid
        and t1.rid = t4.rid
       ) as question,
       t4.response
 from intake_response t4
order by t4.mid, t4.tid, t4.qid, t4.rid
/

prompt
prompt Creating function GETSQLVALUE
prompt =============================
prompt
create or replace function tbicds.getSqlValue (
   pi_vSql                           in varchar2,
   pi_vParameterNameList             in varchar2,
   pi_vParameterValueList            in varchar2
   ) return                             varchar2
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000) := pi_vSql;
   rc                                   sys_refcursor;
   v_vParameterNameList                 varchar2(4000) := trim(pi_vParameterNameList)||',';
   v_vParameterValueList                varchar2(4000) := trim(pi_vParameterValueList)||',';
   v_vParameterName                     varchar2(4000);
   v_vParameterValue                    varchar2(4000);
   v_vValue                             varchar2(4000);
   v_nPos                               number;
   
   function getFirst (
      pio_vList                     in out varchar2
      ) return                             varchar2
   is 
      v_vValue                             varchar2(4000);
      v_nPos                               number;
   begin
      v_nPos := instr(pio_vList,',');
      v_vValue := trim(substr(pio_vList, 1, v_nPos-1));
      pio_vList := trim(substr(pio_vList, v_nPos+1));
      return v_vValue;
   end;
   
begin
   while (v_vParameterNameList is not null)
   loop
      v_vParameterName := getFirst(v_vParameterNameList);
      v_vParameterValue := getFirst(v_vParameterValueList);
      v_vParameterValue := ''''||v_vParameterValue||'''';
      v_vSql := replace(v_vSql, v_vParameterName, v_vParameterValue);
   end loop;
   
   open rc for v_vSql;
   fetch rc into v_vValue;
   close rc;
   
   return v_vValue;
exception
   when others
   then
      return null;
end;
/

prompt
prompt Creating view VW_INTAKE_LOGICVAR_SQL
prompt ====================================
prompt
create or replace view tbicds.vw_intake_logicvar_sql as
select t."VAR_ID",t."IDENTIFIER",t."LOAD_SQL",
       getsqlvalue (t.load_sql, '_ENCRYPT_KEY,_PATIENT_ID', '3936373635303744383842463732333837413645433336313230413037443444,0125AGGJII111201312059') result
 from (select t.var_id, t.identifier, replace(t.load_sql,' from patient ',' from  patient_demographics ') load_sql
      from intake_logicvar_sql t
      ) t
/

prompt
prompt Creating view VW_PATIENT_FX_AUDIT_FREPORT
prompt =========================================
prompt
create or replace view tbicds.vw_patient_fx_audit_freport as
select fx."DB_SESSION_ID",fx."CLIENT_IP",fx."FX_USER_ID",fx."AUDIT_DATE",fx."AUDIT_NAME",fx."AUDIT_DATA", p.patient_id
    from fx_audit fx, patient_demographics p
   where fx.fx_user_id=p.fx_user_id
/

prompt
prompt Creating view VW_RPT_CDE_PATIENT
prompt ================================
prompt
create or replace view tbicds.vw_rpt_cde_patient as
select "PATIENT_ID","FIRST_NAME","MI","LAST_NAME","SSN","GENDER","MARITAL_STATUS_ID","DOB","EDUCATION_LEVEL_ID","PROVIDER_ID","ADDRESS1","ADDRESS2","CITY","POSTAL_CODE","HOMEPHONE","WORKPHONE","EMAIL","STATE_ID","FX_USER_ID","LAST_UPDATED","LAST_UPDATED_BY","PORTAL_USER_ID","WRK_PHONE_CALL","HOME_PHONE_CALL","HOME_PHONE_MSG","EMAIL_MSG","CELLPHONE","CELL_PHONE_CALL","DFN","REGION_ID","SITE_ID","PREFERRED_LANGUAGE_ID","PREFERRED_LANGUAGE_OTHER","DUTY_STATUS_ID","HAND_PREFERENCE_ID"
from patient_demographics t
/

prompt
prompt Creating view VW_UTL_RPT_INTAKE_RESPONSE
prompt ========================================
prompt
create or replace view tbicds.vw_utl_rpt_intake_response as
select t."MID",t."TID",t."QID",t."RID",t."MODULE_DESC", rownum rn from (
select mid, tid, qid, rid, (select acronym||' '||module from intake_module where mid = t.mid) module_desc
from intake_response t
where mid in (
4000,4001,4002,4004,4006,4008,4010,4012,4014,4016,
4018,4020,4022,4024,4026,4028,4030,4032,4034,4036,
4038,4040,4042,4044,4046,4048,4050,4052,4054,4056,
4058,4060,4062,4064,4066,4068,4070,4072,4074,4076,
4078,4080,4082
)
order by mid, tid, qid, rid
) t
/

prompt
prompt Creating package IC_UTL_SEC
prompt ===========================
prompt
create or replace package tbicds.IC_UTL_SEC
AUTHID CURRENT_USER 
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   function digest (
      pi_vData                          in varchar2,
      pi_vKey                           in varchar2
      ) return                             varchar2;

   function encryptData (
      pi_vData                          in varchar2,
      pi_rKey                           in raw,
      pi_vIndex                         in varchar2 default null
      )
      return                               raw;

   function decryptData (
      pi_rData                          in raw,
      pi_rKey                           in raw,
      pi_vIndex                         in varchar2 default null
      )
      return                               varchar2;

  function VarcharToAscii (
     strData            in    varchar2
     ) return varchar2;

end;
/

prompt
prompt Creating package PCK_APP_MENU2
prompt ==============================
prompt
create or replace package tbicds.PCK_APP_MENU2
AUTHID CURRENT_USER 
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/****
Get tool bar items
***/
procedure GetToolbarItemsRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out sys_refcursor);
                              

  /*****
  Gets Menu Root Items
  *****/
  procedure GetMenuRootLevelRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_nAppID           in number,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out sys_refcursor);

  /*****
  Gets Menu Child Items
  *****/
  procedure GetMenuChildItemsRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nAppID           in number,
                                pi_nItemID          in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out sys_refcursor);

  /*****
  Get all menu items for a specific app id
  *****/
  procedure GetAllMenuItemsRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_nAppID           in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out sys_refcursor);

  function fnGetLangPref(pi_nUserID in number) return number;

end PCK_APP_MENU2;
/

prompt
prompt Creating package PCK_AP_USERADMIN
prompt =================================
prompt
create or replace package tbicds.PCK_AP_USERADMIN
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  procedure InsertSuatUser(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_vProviderID      in varchar2,
                           pi_nlocked          in number,
                           pi_vName            in varchar2,
                           pi_vRank            in varchar2,
                           pi_nServiceID       in number,
                           pi_vTitle           in varchar2,
                           pi_vCorps           in varchar2,
                           pi_vSquadron        in varchar2,
                           pi_vOfficeSymbol    in varchar2,
                           pi_vPhone           in varchar2,
                           pi_vEmail           in varchar2,
                           pi_vDimsID          in varchar2,
                           pi_vUIDPWD          in varchar2,
                           pi_nMustChgPwd      in number,
                           pi_vSupervisorID    in varchar2,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2);

  procedure UpdateSuatUser(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_vProviderID      in varchar2,
                           pi_vCurrentDimsID   in varchar2,
                           pi_nlocked          in number,
                           pi_vName            in varchar2,
                           pi_vRank            in varchar2,
                           pi_nServiceID       in number,
                           pi_vTitle           in varchar2,
                           pi_vCorps           in varchar2,
                           pi_vSquadron        in varchar2,
                           pi_vOfficeSymbol    in varchar2,
                           pi_vPhone           in varchar2,
                           pi_vEmail           in varchar2,
                           pi_vDimsID          in varchar2,
                           pi_vUIDPWD          in varchar2,
                           pi_nMustChgPwd      in number,
                           pi_vSupervisorID    in varchar2,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2);

  procedure GetUserRightsRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2,
                            rs                  out sys_refcursor);

  procedure GetUserTypesRS(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out sys_refcursor);

  procedure GetSUATUsersRS(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out sys_refcursor);

  procedure GetUserPermissionsRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_nRights          in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out sys_refcursor);

  procedure GetInternSupervisorsRS(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2,
                                   rs                  out sys_refcursor);

  procedure InsertRightsTemplate(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_nUserType        in number,
                                 pi_nUserRights      in number,
                                 pi_nRightsMode      in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2);

  procedure UpdateRightsTemplate(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_nUserType        in number,
                                 pi_nUserRights      in number,
                                 pi_nRightsMode      in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2);

  procedure GetRightsTemplateRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out sys_refcursor);

end;
/

prompt
prompt Creating package PCK_COMMON
prompt ===========================
prompt
create or replace package tbicds.PCK_COMMON
AUTHID CURRENT_USER 
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  -- Public type declarations
  type refCursor is ref cursor;
  --todo: update righs using entries in STAT_USER_RIGHTS
  c_nNoneUR                          constant binary_integer := 0;   -- 0000000000000000
  c_nDataManagementUR                constant binary_integer := 1;   -- 0000000000000001
  c_nCaseManagementUR                constant binary_integer := 2;   -- 0000000000000010
  c_nPopulationReportingUR           constant binary_integer := 4;   -- 0000000000000100
  c_nTxAssessmentPlanningUR          constant binary_integer := 8;   -- 0000000000001000
  c_nSignNoteUR                      constant binary_integer := 16;  -- 0000000000010000
  c_nCloseNoteUR                     constant binary_integer := 32;  -- 0000000000100000
  c_nProcessNewPatientsUR            constant binary_integer := 64;  -- 0000000001000000
  c_nAdministratorUR                 constant binary_integer := 131072; -- 0000000010000000
  
  c_nMAJCOMUR    constant binary_integer := 32768; --1000000000000000;
  c_nHQUR        constant binary_integer := 32768; --1000000000000000;

  c_nResultStatus_Error   constant binary_integer := 1;
  c_nResultStatus_Success constant binary_integer := 0;

  
  --status codes
  c_nStatus_Success constant number(1) := 1;
  c_nStatus_Error   constant number(1) := 2;
  c_nStatus_Unknown constant number(1) := 3;

  --status texts
  c_vStatus_Default   constant varchar2(255) := '';
  c_vStatus_undefined constant varchar2(255) := 'An undefined error occurred, please contact your system administrator!';

  --are we in debug mode? 1 = yes, 0 = no
  c_nDebug_Mode constant number(1) := 1;

  --used for Enquote Literal
  c_nDoubleTic constant varchar2(2) := '''';

  -- STAT_ACTIVE
  c_nActive   constant number(1) := 1;
  c_nInactive constant number(1) := 2;

  --Active Filter
  c_nFilterActive   constant number(1) := 1;
  c_nFilterInactive constant number(1) := 2;
  c_nShowActiveAll  constant number(1) := 3;

  /*****
  Description:
  helper function used to get age given date of birth
  *****/
  function GetAge(pi_dtDOB in date) return number;

  /*****
  Description:
  helper function used to get a piece of data
  *****/
  function GetPiece(strData      in varchar2,
                    strDelimiter in varchar2,
                    nPosition    in NUMBER) return varchar2;

   /*****
  Description:
  helper function used to get a comma separated value list from a cursor
  *****/
  function join(p_cursor sys_refcursor, p_del varchar2 := ',')
    return varchar2;

end;
/

prompt
prompt Creating package PCK_CPA
prompt ========================
prompt
create or replace package tbicds.PCK_CPA
AUTHID CURRENT_USER 
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

   --type defs to return recordsets
  type RetRefCursor is ref cursor;
  type refCursor is ref cursor;

/****
insert a new pat pw event
***/
procedure InsertPatPWEvent (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
    
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
   
      pi_vEventTitle            in varchar2,
      pi_dtEventDate            in date,
      pi_nAdjustFuture          in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
/******
delete an event
******/  
procedure DeleteEvent (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
    
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      

/******
Check if the user can delete the event
******/  
procedure AllowEventDelete (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
         
      po_nAllowDelete           out number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
/***
Update the pw event info
****/
procedure UpdatePatPWEvent (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      
      pi_vEventTitle            in varchar2,
      pi_dtEventDate            in date,
      pi_nAdjustFuture          in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
/*delete a scheduled module*/
procedure DeletePatPWEventModules (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      pi_vMIDS                  in varchar2,
     
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );


/*****
Gets all pathway event modules associated 
with a specific patient pathway event
******/
procedure GetPWEventModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID             in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/***
insert modules into the pat pw event module list
****/
procedure InsertPatPWEventModules (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      pi_vMIDS                  in varchar2,
      pi_vModuleFors            in varchar2,
     
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
/*****
Gets all clinical program area types
******/
procedure GetCPATypeRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );

/*****
Gets all clinical program areas by region/site
******/
procedure GetCPARS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
 
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*****
Gets all pathways for a clinical program area
******/      
procedure GetCPAPWRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nCPAID                 in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );

/*****
Gets all pathway events for a pathway
******/
procedure GetPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nPWID                  in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*****
Gets all modules for a pathway event
******/
procedure GetPWEventModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nPWID                  in number,
      pi_nPWEventID             in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor  
      );


/*****
Gets all events and modules for a pathway 
******/
procedure GetPWEventAndModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nPWID                  in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
----USER tables----------------------------------------------------

/*****
update a users default clinical program area
******/
procedure UpdateUserDefaultCPA (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nCPAID                 in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
                       
/*****
Gets a users clinical program areas
******/
procedure GetUserCPARS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );

----PATIENT tables-------------------------------------------------


/*****
Gets ALL pathways associated with a patient, 
ordered by clinical program area
******/
procedure GetPatPWRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );


/*****
Check if the Event is Read-Only
******/
procedure IsPatPWEventReadOnly (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
      pi_nPatPWEventID          in number,
      po_nIsReadOnly            out number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
/*****
Gets all pathway events for a specific patient pathway
******/
procedure GetPatPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWID                  in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*****
Gets all pathway events associated with a patient
******/
procedure GetPatPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*****
Gets one pathway event associated with a patient
******/
procedure GetPatPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*****
Gets all pathway event modules associated 
with a specific patient pathway event
******/
procedure GetPatPWEventModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
      pi_nPatPWEventID             in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );

/*****
Gets all pathway event modules associated with a patient 
******/
procedure GetPatPWEventModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
       
/*get all modules for a patient pw event*/
procedure GetPatPWEventModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID             in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
----------operations---------------

/*****
Updates Patient Event Module status after a module is completed
*****/
procedure UpdatePatPWEventModule (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPWID                  in number,
      pi_nPatPWEvtID            in number,
      pi_nMID                   in number,
      pi_nIntakeID              in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      ); 
      
procedure UpdatePatPWEventModule (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPWID                  in number,
      pi_nPatPWEvtID            in number,
      pi_nMID                   in number,
      pi_nIntakeID              in number,
      pi_nPwEvtModID              in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );     
            
/******
apply a pathway/schedule to a patient
******/      
procedure ApplyPathway (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      
      pi_vPWIDs                 in varchar2,
      pi_vPWTitle               in varchar2,
      pi_dtBaseline             in date,
      
      po_nPatPWID               out number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
            
procedure ApplyDefaultPathway (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );

procedure InsertPatPWEventModules (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      pi_vMIDS                  in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
procedure UpdatePatPWEventModules (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      
      pi_vEventTitle            in varchar2,
      pi_dtEventDate            in date,
      pi_nAdjustFuture          in number,
 
      pi_vMIDS                  in varchar2,
      pi_vModuleFors            in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
  
            
end PCK_CPA;
/

prompt
prompt Creating package PCK_DEMOGRAPHICS
prompt =================================
prompt
create or replace package tbicds.PCK_DEMOGRAPHICS
AUTHID CURRENT_USER
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

  --recordsets
  type RetRefCursor is ref cursor;

  procedure GetRelationshipSelfRS(
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2,
      rs                  out RetRefCursor
      );

  procedure GetStateRS(
                       pi_vSessionID       in varchar2,
                       pi_vSessionClientIP in varchar2,
                       pi_nUserID          in number,
                       po_nStatusCode      out number,
                       po_vStatusComment   out varchar2,
                       rs                  out RetRefCursor
                       );

  procedure GetGenderRS(
                        pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        po_nStatusCode      out number,
                        po_vStatusComment   out varchar2,
                        rs                  out RetRefCursor
                        );

  procedure GetGenderDescByIdRS (
      pi_vSessionID              in varchar2,
      pi_vSessionClientIP        in varchar2,
      pi_nUserID                 in number,
      pi_vGenderID               in varchar2,
      po_nStatusCode             out number,
      po_vStatusComment          out varchar2,
      rs                         out RetRefCursor
      );

end;
/

prompt
prompt Creating package PCK_UTL_COMMON
prompt ===============================
prompt
create or replace package tbicds.PCK_UTL_COMMON
AUTHID CURRENT_USER
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   -- Public type declarations
   type refCursor is ref cursor;

   -- Public constant declarations
   c_nResultStatus_Error       constant number := 1;
   c_nResultStatus_Success     constant number := 0;

end;
/

prompt
prompt Creating package PCK_ENCOUNTER_INTAKE
prompt =====================================
prompt
create or replace package tbicds.PCK_ENCOUNTER_INTAKE
AUTHID CURRENT_USER
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

  --custom to return recordsets
  type RetRefCursor is ref cursor;

  function GetPiece(strData      in varchar2,
                    strDelimiter in varchar2,
                    nPosition    in NUMBER) return varchar2;

  procedure GetEncounterFlags(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vEncounterID     in varchar2,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out Pck_Utl_Common.refCursor);

  procedure GetEncounterIntakeFlags(pi_vSessionID         in varchar2,
                                    pi_vSessionClientIP   in varchar2,
                                    pi_nUserID            in number,
                                    pi_vEncounterID       in varchar2,
                                    pi_vEncounterIntakeID in number,
                                    po_nStatusCode        out number,
                                    po_vStatusComment     out varchar2,
                                    rs                    out Pck_Utl_Common.refCursor);

  procedure getIntakeAltLang(pi_vSessionID         in varchar2,
                             pi_vSessionClientIP   in varchar2,
                             pi_nUserID            in number,
                             pi_vEncounterID       in varchar2,
                             pi_nEncounterIntakeID in number,
                             po_nOutAltLang        out number,
                             po_nStatusCode        out number,
                             po_vStatusComment     out varchar2);

  procedure getIntakePatientID(pi_vSessionID         in varchar2,
                               pi_vSessionClientIP   in varchar2,
                               pi_nUserID            in number,
                               pi_vEncounterID       in varchar2,
                               pi_nEncounterIntakeID in number,
                               po_vPatientID         out varchar2,
                               po_nStatusCode        out number,
                               po_vStatusComment     out varchar2);

  -----------------------------------------------------------
  -- Tries to retrieve the encounter ID for the passed MID.
  -- If there is no encounter, it inserts a new encounter
  -- of type 7 (patient intake session)
  -----------------------------------------------------------
  procedure GetEncounterIDFromModule(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     pi_nModuleID        in number,
                                     pi_vPatientID       in varchar2,
                                     pi_nTreatmentID     in number,
                                     po_vEncounterID     out varchar2,
                                     po_nStatusCode      out number,
                                     po_vStatusComment   out varchar2);

  -- Checks to see if there is an encounter_intake for the module
  -- if not, it inserts new one
  procedure NewEncounterIntake(pi_vSessionID         in varchar2,
                               pi_vSessionClientIP   in varchar2,
                               pi_nUserID            in number,
                               pi_nModuleID          in number,
                               pi_vEncounterID       in varchar2,
                               pi_nAltLang           in number,
                               po_nEncounterIntakeID out number,
                               po_nStatusCode        out number,
                               po_vStatusComment     out varchar2);

  --get all Encounter Intake Responses
  procedure GetResponsesCountRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vEncounterID     in varchar2,
                                pi_vMIDs            in varchar2,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor);

  procedure GetIntakesForEducationRS(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     pi_vPatientID       in varchar2,
                                     po_nStatusCode      out number,
                                     po_vStatusComment   out varchar2,
                                     rs                  out RetRefCursor);

  procedure GetIntakesForReviewRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  pi_vPatientID       in varchar2,
                                  pi_vEncounterID      in varchar2,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor);

end;
/

prompt
prompt Creating package PCK_FX_SEC
prompt ===========================
prompt
create or replace package tbicds.PCK_FX_SEC AUTHID CURRENT_USER is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

  /*
  created a database session for a user. used after a successful login to an external
  system such as MDWS to establish a session for the user in the database
  */
  procedure CreateSession(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vWebSessionID    in varchar2,
                          po_vDBSessionID     out varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2);

  --custom to return recordsets
  type RetRefCursor is ref cursor;

  --session values
  procedure DeleteSessionValue(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vKey             in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2);
  procedure GetSessionValue(pi_vDBSessionID     in varchar2,
                            pi_vWebSessionID    in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vKey             in varchar2,
                            po_vKeyValue        out varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2);
  procedure SetSessionValue(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vKey             in varchar2,
                            pi_vKeyValue        in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2);

  /*audits a transaction to the syslog*/
  procedure SysLogAuditTransaction(pi_vSessionID in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_nStatus          in number,
                                   pi_vAuditXML        in varchar2,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2);
                                   
  procedure DeleteAllSessionValues(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2);

  --auditing
  procedure AuditPageAccess(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vPageName        in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2);

  
  --login and return a databsae session id
  procedure Login(pi_vSessionID       in varchar2,
                  pi_vSessionClientIP in varchar2,
                  pi_nUserID          in number, --not used but passed in to maintain consistant default param list
                  pi_vUserName        in varchar2,
                  pi_vPassword        in varchar2,
                  pi_vCert            in varchar2,
                  po_nUserID          out number,
                  po_vDBSessionID     out varchar2,
                  po_nTimeout         out number,
                  po_nStatusCode      out number,
                  po_vStatusComment   out varchar2);

  --login and return a databsae session id
  procedure Sign(pi_vSessionID       in varchar2,
                 pi_vSessionClientIP in varchar2,
                 pi_nUserID          in number,
                 pi_vUserName        in varchar2,
                 pi_vPassword        in varchar2,
                 po_vProviderID      out varchar2,
                 po_nUserType        out number,
                 po_nStatusCode      out number,
                 po_vStatusComment   out varchar2);

  procedure ValidatePassword(pi_vKey           in varchar2,
                             pi_nUserID        in number,
                             pi_vUserName      in varchar2,
                             pi_vOldPassword   in varchar2,
                             pi_vPassword      in varchar2,
                             pi_vCOldPassword  in varchar2,
                             pi_vCPassword     in varchar2,
                             pi_vCUserName     in varchar2,
                             pi_nResetPassword in number,
                             po_nStatusCode    out number,
                             po_vStatusComment out varchar2);

  --user change password and login
  procedure ChangePassword(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number, --not used but passed in to maintain consistant default param list
                           pi_vKey             in varchar2,
                           pi_vUserName        in varchar2,
                           pi_vOldPassword     in varchar2,
                           pi_vPassword        in varchar2,
                           pi_vCert            in varchar2,
                           pi_vCOldPassword    in varchar2,
                           pi_vCPassword       in varchar2,
                           pi_vCUserName       in varchar2,
                           po_nUserID          out number,
                           po_vDBSessionID     out varchar2,
                           po_nTimeout         out number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2);

  --logoff
  procedure LogOff(pi_vSessionID       in varchar2,
                   pi_vSessionClientIP in varchar2,
                   pi_nUserID          in number,
                   po_nStatusCode      out number,
                   po_vStatusComment   out varchar2);

  --get fx_user record by encrypted uid
  procedure GetFXUserRS(pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        pi_vEncUID          in varchar2,
                        po_nStatusCode      out number,
                        po_vStatusComment   out varchar2,
                        rs                  out RetRefCursor);

  --audit a transaction
  procedure AuditTransaction(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vKey             in varchar2,
                             pi_vSPName          in varchar2,
                             pi_clAuditXML       in clob,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2);

  --insert a new fx_user
  procedure InsertFXUser(pi_vSessionID       in varchar2,
                         pi_vSessionClientIP in varchar2,
                         pi_nUserID          in number,
                         pi_vKey             in varchar2,
                         pi_vProviderID      in varchar2,
                         pi_vUserName        in varchar2,
                         pi_vPassword        in varchar2,
                         pi_nAccountLocked   in number,
                         pi_nAccountInactive in number,
                         
                         pi_vCOldPassword in varchar2,
                         pi_vCPassword    in varchar2,
                         pi_vCUserName    in varchar2,
                         
                         po_nFXUserID      out number,
                         po_nStatusCode    out number,
                         po_vStatusComment out varchar2);

  --update an fx_user record
  procedure UpdateFXUser(pi_vSessionID       in varchar2,
                         pi_vSessionClientIP in varchar2,
                         pi_nUserID          in number,
                         pi_nFXUserID        in number,
                         pi_vProviderID      in varchar2,
                         pi_vUserName        in varchar2,
                         pi_vPassword        in varchar2,
                         pi_nAccountLocked   in number,
                         pi_nAccountInactive in number,
                         po_nStatusCode      out number,
                         po_vStatusComment   out varchar2);

  procedure UpdateFXUserRights(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_nFxUserID        in number,
                               pi_nUserType        in number,
                               pi_nUserRights      in number,
                               pi_nUserReadOnly    in number,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2);

  --update an fx_user record
  procedure UpdateFXUserPWD(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vKey             in varchar2,
                            pi_nFXUserID        in number,
                            pi_vUserName        in varchar2,
                            pi_vPassword        in varchar2,
                            pi_nAccountLocked   in number,
                            pi_nAccountInactive in number,
                            
                            pi_vCPassword in varchar2,
                            pi_vCUserName in varchar2,
                            
                            po_nStatusCode    out number,
                            po_vStatusComment out varchar2);

  --update an fx_user record
  procedure UpdateFXUserOptions(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nFXUserID        in number,
                                pi_nAccountLocked   in number,
                                pi_nAccountInactive in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2);

  procedure GetFXUsernamePasswordRS(pi_vSessionID       in varchar2,
                                    pi_vSessionClientIP in varchar2,
                                    pi_nUserID          in number,
                                    pi_vProviderID      in varchar2,
                                    po_nStatusCode      out number,
                                    po_vStatusComment   out varchar2,
                                    rs                  out RetRefCursor);

  procedure GetFXUserIdRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vProviderID      in varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor);

  procedure CheckFXUserRecRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vProviderID      in varchar2,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor);

   procedure GetUserQuestions(pi_vSessionID       in varchar2,
  pi_vSessionClientIP in varchar2,
  pi_nUserID          in number,
  --
  pi_vUsername in varchar2,
  --                                 
  po_nStatusCode    out number,
  po_vStatusComment out varchar2,
  rs                out RetRefCursor); 

  procedure UpdateSecQuestions(pi_vSessionID       in varchar2,
  pi_vSessionClientIP in varchar2,
  pi_nUserID          in number,
  
  pi_nQuestionID_1 in number,
  pi_vAnswer_1     in varchar2,
  
  pi_nQuestionID_2 in number,
  pi_vAnswer_2     in varchar2,
  
  pi_nQuestionID_3 in number,
  pi_vAnswer_3     in varchar2,
  
  po_nStatusCode    out number,
  po_vStatusComment out varchar2);

  procedure CheckSecurityQuestions(pi_vSessionID       in varchar2,
  pi_vSessionClientIP in varchar2,
  pi_nUserID          in number,
  
  --pi_nQuestionID_1 in number,
  pi_vAnswer_1 in varchar2,
  
  --pi_nQuestionID_2 in number,
  pi_vAnswer_2 in varchar2,
  
  --pi_nQuestionID_3 in number,
  pi_vAnswer_3 in varchar2,
  
  po_nStatusCode    out number,
  po_vStatusComment out varchar2); 

  procedure ResetPassword(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vKey             in varchar2,
                          pi_nFXUserID        in number,
                          pi_vUserName        in varchar2,
                          pi_vPassword        in varchar2,
                          pi_vCPassword       in varchar2,
                          pi_vCUserName       in varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2);

  procedure GetSecurityQuestions(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_nQuestionGrp     in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor);

end PCK_FX_SEC;
/

prompt
prompt Creating package PCK_FX_SEC_PATIENT
prompt ===================================
prompt
create or replace package tbicds.PCK_FX_SEC_PATIENT
AUTHID CURRENT_USER
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

 --custom to return recordsets
  type RetRefCursor is ref cursor;

   /* checks if a portal account exists for the patient */
   procedure CheckPatientFXUserRecRS( pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      pi_vKey             in varchar2,
                                      pi_vPatientID       in varchar2,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2,
                                      rs                  out RetRefCursor);

   /* gets a FXUserID given the patient */
   procedure GetPatientFXUserIdRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  pi_vKey in varchar2,
                                  pi_vPatientID      in varchar2,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor);

   /* gets the encrypted username/password pair for the patient */
   procedure GetPatientFXUsernamePasswordRS(pi_vSessionID       in varchar2,
                                            pi_vSessionClientIP in varchar2,
                                            pi_nUserID          in number,
                                            pi_vKey in varchar2,
                                            pi_vPatientID       in varchar2,
                                            po_nStatusCode      out number,
                                            po_vStatusComment   out varchar2,
                                            rs                  out RetRefCursor);

   /* updates the patient portal account */
   procedure InsertPatientFXUser (pi_vSessionID              in varchar2,
                                  pi_vSessionClientIP        in varchar2,
                                  pi_nUserID                 in number,
                                  pi_vKey in varchar2,
                                  pi_vPatientID              in varchar2,
                                  pi_vUserName               in varchar2,
                                  pi_vPassword               in varchar2,
                                  pi_nAccountLocked          in number,
                                  pi_nAccountInactive        in number,
                                  pi_vCOldPassword           in varchar2,
                                  pi_vCPassword              in varchar2,
                                  pi_vCUserName              in varchar2,   
                                  po_nFXUserID               out number,
                                  po_nStatusCode             out number,
                                  po_vStatusComment          out varchar2);

   /* updates the patient portal account password*/
   procedure UpdatePatientFXUserPWD(pi_vSessionID              in varchar2,
                                    pi_vSessionClientIP        in varchar2,
                                    pi_nUserID                 in number,
                                    pi_vKey in varchar2,
                                    pi_nFXUserID               in number,
                                    pi_vUserName               in varchar2,
                                    pi_vPassword               in varchar2,
                                    pi_nAccountLocked          in number,
                                    pi_nAccountInactive        in number,
                                    pi_vCPassword              in varchar2,
                                    pi_vCUserName              in varchar2,
                                    po_nStatusCode             out number,
                                    po_vStatusComment          out varchar2);
                  
   /* updates the patient portal account options */
   procedure UpdatePatientFXUserOptions(pi_vSessionID              in varchar2,
                                        pi_vSessionClientIP        in varchar2,
                                        pi_nUserID                 in number,
                                        pi_nFXUserID               in number,
                                        pi_nAccountLocked          in number,
                                        pi_nAccountInactive        in number,
                                        po_nStatusCode             out number,
                                        po_vStatusComment          out varchar2);


end;
/

prompt
prompt Creating package PCK_INSTRUMENT_RESPONSES
prompt =========================================
prompt
create or replace package tbicds.PCK_INSTRUMENT_RESPONSES
AUTHID CURRENT_USER 
is

/* Copyright 2015 Intellica Corporation.  

This software is protected by FAR Subpart 27.4 - Rights in Data and Copyrights and 
international treaties.  The software was produced by Intellica Corporation of 
San Antonio, Texas for the Veterans Administration (VA) under Contract Number 
VA118-14-C-0015, Project Number TAC-16-28335 and Project Title, 
'Traumatic Brain Injury Clinical Decision Support (TBI CDS) Implementation'.  
Contract dates: 8 May 2014 - 4 January 2016.  This software was finalized 
and uploaded to the VA's Open Source Electronic Health Record Alliance (OSEHRA) 
on 31 December 2015.  Unauthorized reproduction or distribution of this software 
or any portion of it may result in severe civil and criminal penalties and will 
be prosecuted to the maximum possible extent of the law.

For licensing information contact:  info@intellicacorp.com 
*/

  function fnGetExportScoreValue(pi_vDataValue  in varchar2,
                                 pi_vStatFilter in varchar2) return varchar2;
                                    
  procedure InsertInstrumentResponse(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     
                                     pi_vPatientID     in varchar2,
                                     pi_nIntakeID      in number,
                                     pi_nMID           in number,
                                     pi_nTID           in number,
                                     pi_nQID           in number,
                                     pi_nRID           in number,
                                     pi_nScoreValue    in number,
                                     pi_vResponseValue in varchar2,

                                     po_nStatusCode    out number,
                                     po_vStatusComment out varchar2);

  procedure GetInstrumentResponsesRS(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     
                                     pi_vPatientID      in varchar2,
                                     --pi_nSiteID         in number,
                                     --pi_nClinicalProgID in number,
                                     --pi_nPathwayID      in number,
                                     pi_nMID            in number,
                                     pi_nIntakeID       in number,
                                     
                                     rs                out PCK_COMMON.refCursor,
                                     po_nStatusCode    out number,
                                     po_vStatusComment out varchar2);
                                     
 procedure GetMergedInstrumentResponsesRS(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     
                                     pi_vPatientID      in varchar2,
                                     pi_nMID            in number,
                                     pi_nIntakeID       in number,
                                     
                                     rs                out PCK_COMMON.refCursor,
                                     po_nStatusCode    out number,
                                     po_vStatusComment out varchar2);

  PROCEDURE GetIntakeLogicVarRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vPatientID       in varchar2,
                                pi_vKey             in varchar2,
                                pi_nMID             in number,
                                rs                  out PCK_COMMON.refCursor,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2);

  procedure GetScoreLogicRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_nMID             in number,
                            rs                  out PCK_COMMON.refCursor,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2);

  PROCEDURE GetPatientInstrumentsRS(pi_vSessionID       IN VARCHAR2,
                                    pi_vSessionClientIP IN VARCHAR2,
                                    pi_nUserID          IN NUMBER,
                                    pi_vPatientID       IN VARCHAR2,
                                    rs                  OUT PCK_COMMON.refCursor,
                                    po_nStatusCode      OUT NUMBER,
                                    po_vStatusComment   OUT VARCHAR2);

 procedure RemoveAllResponses(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vPatientID       in varchar2,
                              pi_nMID             in number,
                              pi_nIntakeID        in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2);
                                                                   
 procedure RemovePrevResponses(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vPatientID       in varchar2,
                               pi_nMID             in number,
                               pi_nIntakeID        in number,
                               pi_vResponses       in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2); 
                               
 procedure RemoveResponse(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vPatientID       in varchar2,
                          pi_nMID             in number,
                          pi_nIntakeID        in number,
                          pi_nRID             in number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2);
                         
  procedure InsertInstrumentScore(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                     
                                 pi_vPatientID       in varchar2,
                                 pi_nIntakeID        in number,
                                 pi_nMID             in number,
                                 pi_nSeriesID        in number,
                                 pi_nScore           in number,
                                 pi_vInterpret       in varchar2,
                                     
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2);
                                 
 procedure InsertInstrumentScore(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                     
                                 pi_vPatientID       in varchar2,
                                 pi_nIntakeID        in number,
                                 pi_nMID             in number,
                                 pi_nSeriesID        in number,
                                 pi_nScore           in number,
                                 pi_vInterpret       in varchar2,
                                 pi_vDescription     in varchar2,
                                     
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2);
                                 
 procedure InsertInstrumentScore(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                     
                                 pi_vPatientID       in varchar2,
                                 pi_nIntakeID        in number,
                                 pi_nMID             in number,
                                 pi_nSeriesID        in number,
                                 pi_nScore           in number,
                                 pi_vInterpret       in varchar2,
                                 pi_vDescription     in varchar2,
                                 pi_nSeverity        in number,
                                     
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2);
                                 
   procedure DeleteInstrumentScore(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP  in varchar2,
                                   pi_nUserID           in number,
                                       
                                   pi_vPatientID        in varchar2,
                                   pi_nIntakeID         in number,
                                   pi_nMID              in number,
                                       
                                   po_nStatusCode       out number,
                                   po_vStatusComment    out varchar2);

  procedure GetInstrumentScoresRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                       
                                  pi_vPatientID       in varchar2,
                                  pi_nMID             in number,
                                  pi_nIntakeID        in number,
                                  pi_nFilter          in number,
                                       
                                  rs                  out PCK_COMMON.refCursor,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2);
                                  
  procedure GetInstrumentScoresRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                       
                                  pi_vPatientID      in varchar2,
                                  pi_nMID            in number,
                                  pi_nIntakeID       in number,
                                       
                                  rs                out PCK_COMMON.refCursor,
                                  po_nStatusCode    out number,
                                  po_vStatusComment out varchar2);
                                   
  procedure GetInstrumentScoresRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                       
                                  pi_vPatientID      in varchar2,
                                  pi_nMID            in number,
                                       
                                  rs                out PCK_COMMON.refCursor,
                                  po_nStatusCode    out number,
                                  po_vStatusComment out varchar2);
                                 
end PCK_INSTRUMENT_RESPONSES;
/

prompt
prompt Creating package PCK_INTAKE
prompt ===========================
prompt
create or replace package tbicds.PCK_INTAKE AUTHID CURRENT_USER is

/* Copyright 2015 Intellica Corporation.  

This software is protected by FAR Subpart 27.4 - Rights in Data and Copyrights and 
international treaties.  The software was produced by Intellica Corporation of 
San Antonio, Texas for the Veterans Administration (VA) under Contract Number 
VA118-14-C-0015, Project Number TAC-16-28335 and Project Title, 
'Traumatic Brain Injury Clinical Decision Support (TBI CDS) Implementation'.  
Contract dates: 8 May 2014 - 4 January 2016.  This software was finalized 
and uploaded to the VA's Open Source Electronic Health Record Alliance (OSEHRA) 
on 31 December 2015.  Unauthorized reproduction or distribution of this software 
or any portion of it may result in severe civil and criminal penalties and will 
be prosecuted to the maximum possible extent of the law.

For licensing information contact:  info@intellicacorp.com 
*/
  --custom to return recordsets
  type RetRefCursor is ref cursor;


 /*****
  Delete Instrument 
  *****/
  procedure DeleteInstrument(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP  in varchar2,
                             pi_nUserID           in number,
                                     
                             pi_vPatientID        in varchar2,
                             pi_nIntakeID         in number,
                             pi_nMID              in number,
                             pi_nPWEventModuleID  in number,
                                     
                             po_nStatusCode       out number,
                             po_vStatusComment    out varchar2);

/*get rs of modules that are scoreable*/

procedure GetAllScorableModuleRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2,
                            rs                  out RetRefCursor);
                             
  
  /*get module type*/
  procedure GetModuleType(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_nMID             in number,
                          po_nModuleType      out number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2);
                        
  /*get intake modules by group id*/
  procedure GetModuleGroupMIDRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nModuleGroupID   in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor);

  /*get intake modules by group id and perform an inner search*/
  procedure GetModuleGroupMIDRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nModuleGroupID   in number,
                                pi_vSearch          in varchar2,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor);
                                
  /*get module groups by group type id*/
  procedure GetModuleGroupRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_nGroupTypeID     in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor);

  /*get module group types such as domain and clinical setting*/
  procedure GetModuleGroupTypeRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor);

  procedure GetResponseLoadRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vLoadTable       in varchar2,
                              pi_vLoadField       in varchar2,
                              pi_vLoadFilter      in varchar2,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out RetRefCursor);

  procedure GetIntakeModulesRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor);

  procedure GetModuleGroupRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor);

  procedure GetModulesListRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor);

  procedure StartModule(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           
                           pi_vPatientID in varchar2,
                           pi_nMID       in number,
                           pi_nGroupID   in number,
                           pi_nIntakeID  in number,
                           
                           po_nStatusCode    out number,
                           po_vStatusComment out varchar2);
                           
  -- *****************************************************
  -- MARK MODULE COMPLETE
  procedure CompleteModule(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           
                           pi_vPatientID in varchar2,
                           pi_nMID       in number,
                           pi_nGroupID   in number,
                           pi_nIntakeID  in number,
                           
                           po_nStatusCode    out number,
                           po_vStatusComment out varchar2);

  -- *****************************************************
  -- INSERT ENCOUNTER INTAKE 
  

  -- *****************************************************
  -- Insert Encounter Intake Score


/*get rs of modules matching search criteria*/
procedure GetAllModuleRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2,
                            rs                  out RetRefCursor);
  

/*get rs of modules matching search criteria*/
procedure GetModuleSearchRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vSearch          in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2,
                            rs                  out RetRefCursor);

PROCEDURE GetScoreDataStringRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_vPatientID       in varchar2,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor);
                                      
procedure GetNextMIDIntakeIDRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP   in varchar2,
                             pi_nUserID            in number,
                             pi_vPatientID          in varchar2,
                             pi_nMID                in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor) ;

end;
/

prompt
prompt Creating package PCK_MESSAGES
prompt =============================
prompt
create or replace package tbicds.PCK_MESSAGES
AUTHID CURRENT_USER
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --return recordsets
  type RetRefCursor is ref cursor;

  procedure GetUserMessagesRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vKey             in varchar2,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out RetRefCursor);

  procedure GetDeletedMessagesRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_vKey             in varchar2,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor);

  procedure GetUnreadMessagesRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor);

  procedure GetSentMessagesRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vKey             in varchar2,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out RetRefCursor);

  procedure GetRecipientsListRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nMessageID       in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor);

  procedure SendMessage(pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        
                        pi_vKey        in varchar2,
                        pi_vRecipients in varchar2,
                        pi_vSubject    in varchar2,
                        pi_clobBody    in clob,
                        po_nMessageID  out number,
                        
                        po_nStatusCode    out number,
                        po_vStatusComment out varchar2);

  procedure MarkAsRead(pi_vSessionID       in varchar2,
                       pi_vSessionClientIP in varchar2,
                       pi_nUserID          in number,
                       pi_nMessageID       in number,
                       po_nStatusCode      out number,
                       po_vStatusComment   out varchar2);

  procedure MarkAsDeleted(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_nMessageID       in number,
                          pi_nIsSentMsg       in number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2);

  procedure GetProviderPatientsRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  pi_vKey             in varchar2,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor);

  procedure GetAllProviderRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor);

  function fGetRecipientsList(pi_vKey in varchar2, pi_nMessageID varchar2)
    return varchar2;

  procedure BulkSendMessages(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             
                             pi_nMessageID in number,
                             pi_vRecipient in varchar2,
                             pi_vSubject   in varchar2,
                             pi_clobBody   in clob,
                             
                             po_nStatusCode    out number,
                             po_vStatusComment out varchar2);

  -- **************************************************************
  --  SEND EXTERNAL MESSAGE NOTIFICATION
  procedure SendExternalNotification(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     pi_vKey             in varchar2,
                                     pi_nMessageID       in number,
                                     po_nStatusCode      out number,
                                     po_vStatusComment   out varchar2);

end;
/

prompt
prompt Creating package PCK_MILITARY
prompt =============================
prompt
create or replace package tbicds.PCK_MILITARY
AUTHID CURRENT_USER
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --return recordsets
  type RetRefCursor is ref cursor;

  --get a record set back
  procedure GetMilitaryServiceRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor);


  procedure GetMilitaryDutyStationRS(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     po_nStatusCode      out number,
                                     po_vStatusComment   out varchar2,
                                     rs                  out RetRefCursor);

end;
/

prompt
prompt Creating package PCK_NOTE
prompt =========================
prompt
create or replace package tbicds.PCK_NOTE
AUTHID CURRENT_USER 
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/  
  --type defs to return recordsets
  type RetRefCursor is ref cursor;
  type refCursor is ref cursor;
  










-----------------------------------------------------------
------TODO remove the following once its confirmed 
------they are not in use...
------------------------------------------------

/*****
Description: Gets all cosigners for a site/region
******/
procedure GetCosignerRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vSearch                in varchar2,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*****
Description: Gets all clinics for a site/region
******/
procedure GetClinicRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vSearch                in varchar2,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      

/*****
Description: Gets all note titles for a site/region
******/
procedure GetNoteTitleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vSearch                in varchar2,
       
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*****
Description: Gets all patient appointments for a site/region/dfn
******/
procedure GetPatientAppointmentRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      pi_dtFrom                 in date,
      pi_dtTo                   in date,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
      
/*****
Description: Gets all patient visits for a site/region/dfn
******/
procedure GetPatientVisitRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      pi_dtFrom                 in date,
      pi_dtTo                   in date,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*****
Description: Gets all patient consults for a site/region/dfn
******/
procedure GetPatientConsultRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      pi_dtFrom                 in date,
      pi_dtTo                   in date,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*****
Description: Gets all patient admissions for a site/region/dfn
******/
procedure GetPatientAdmissionRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      pi_dtFrom                 in date,
      pi_dtTo                   in date,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      


     




end PCK_NOTE;
/

prompt
prompt Creating package PCK_NOTE_PREFILL
prompt =================================
prompt
create or replace package tbicds.PCK_NOTE_PREFILL
AUTHID CURRENT_USER
is
/* Copyright 2015 Intellica Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  -- Public type declarations
  type RetRefCursor is ref cursor;

  function fnGetOutcomesReviewedList(pi_vPatientID       in varchar2,
                                     pi_nPatPWEventID    in number) return varchar2;

  function fnGetOutcomesReviewedList2(pi_vPatientID      in varchar2,
                                      pi_nPatPWEventID   in number) return clob;

  function fnGetOutcomesNotes(pi_vPatientID              in varchar2,
                              pi_nPatPWEventID           in number) return varchar2;

--  function fnGetQuestionResponse(pi_vPatientID in varchar2,
--                                 pi_nMID       in number,
--                                 pi_nTID       in number,
--                                 pi_nQID       in number,
--                                 pi_nModGroup  in number) return varchar2;
--
--  function fnGetQuestionScore(pi_vPatientID in varchar2,
--                              pi_nMID       in number,
--                              pi_nTID       in number,
--                              pi_nQID       in number,
--                              pi_nModGroup  in number) return varchar2;
--
  function fnGetQuestionResponseList(pi_vPatientID        in varchar2,
                                     pi_nModuleIdentifier in varchar2,
                                     pi_nTID              in number,
                                     pi_nQID              in number) return varchar2;

  function fnGetModuleResponses(pi_vPatientID        in varchar2,
                                pi_nModuleIdentifier in varchar2) return clob;

  function fnGetModuleResponses(pi_vPatientID        in varchar2,
                                pi_nModuleIdentifier in varchar2,
                                pi_nIntakeID         in number) return clob;

  function fnGetModuleScore(pi_vPatientID  in varchar2,
                            pi_nMID        in number,
                            pi_nIntakeID   in number) return clob;

  function fnGetAllCompletedModules(pi_vPatientID  in varchar2,
                                    pi_nPatPWEventID in number) return clob;
--
--  function fnGetResponseByID(pi_vPatientID in varchar2,
--                             pi_nMID       in number,
--                             pi_nTID       in number,
--                             pi_nQID       in number,
--                             pi_nRID       in number,
--                             pi_nModGroup  in number) return varchar2;
--
--  function fnHasResponse(pi_vPatientID in varchar2,
--                         pi_nMID       in number,
--                         pi_nTID       in number,
--                         pi_nQID       in number,
--                         pi_nModGroup  in number) return number;
--
--  function fnHasResponseByID(pi_vPatientID in varchar2,
--                             pi_nMID       in number,
--                             pi_nTID       in number,
--                             pi_nQID       in number,
--                             pi_nRID       in number,
--                             pi_nModGroup  in number) return number;
--
--  function fnGetScore(pi_vPatientID in varchar2,
--                      pi_nMID       in number,
--                      pi_nModGroup  in number,
--                      pi_nInterpret in number) return varchar2;
--
--  function fnGetScoreData(pi_vPatientID in varchar2,
--                          pi_nMID       in number,
--                          pi_nModGroup  in number,
--                          pi_nInterpret in number) return varchar2;
--
--  function fnGet1MOTxSymptoms(pi_vPatientID in varchar2,
--                              pi_nMID       in number,
--                              pi_nGroup1    in number,
--                              pi_nGroup2    in number) return varchar2;
--
--  function fnGet1MOOSASymptoms(pi_vPatientID in varchar2,
--                               pi_nMID       in number,
--                               pi_nGroup1    in number,
--                               pi_nGroup2    in number) return varchar2;
--
--  function fnGet3MOTxSymptoms(pi_vPatientID in varchar2,
--                              pi_nMID       in number,
--                              pi_nGroup1    in number,
--                              pi_nGroup2    in number) return varchar2;
--
--  function fnGet3MOOSASymptoms(pi_vPatientID in varchar2,
--                               pi_nMID       in number,
--                               pi_nGroup1    in number,
--                               pi_nGroup2    in number) return varchar2;
--
--  function fnGet1WKTxSymptoms(pi_vPatientID in varchar2,
--                              pi_nMID       in number,
--                              pi_nGroup1    in number,
--                              pi_nGroup2    in number) return varchar2;
--
--  function fnGet1WKOSASymptoms(pi_vPatientID in varchar2,
--                               pi_nMID       in number,
--                               pi_nGroup1    in number,
--                               pi_nGroup2    in number) return varchar2;
--
--  function fnPAPUsage(pi_vPatientID in varchar2) return varchar2;
--
--  function fnGetTimeDescription(minutes in number) return varchar2;
--
--   function fnGetPatientBMI(pi_vPatientID in varchar2, pi_nGroupID in number) return varchar2;

end;
/

prompt
prompt Creating package PCK_PATIENT
prompt ============================
prompt
create or replace package tbicds.PCK_PATIENT AUTHID CURRENT_USER is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  type RetRefCursor is ref cursor;

  procedure InitialEncounter(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vPatientID       in varchar2,
                             po_nInitialEnc      out number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2);

  --get a record set of patients back that match criteria
  procedure GetPatientLookupRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vKey             in varchar2,
                               pi_nSelectedCases   in number,
                               pi_nSearchType      in number,
                               pi_vSearchValue     in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor);

  --gets basic patient demographic data given the patients fx_user_id
  procedure GetPatientIDRS(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_vKey             in varchar2,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out RetRefCursor);

  procedure GetPatientDemographicsRS(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     pi_vKey             in varchar2,
                                     pi_vPatientID       in varchar2,
                                     po_nStatusCode      out number,
                                     po_vStatusComment   out varchar2,
                                     rs                  out RetRefCursor);

  procedure InsertPatientDemographics(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      --Patient Table
                                      pi_vKey            in varchar2,
                                      pi_vPatientID      in varchar2,
                                      pi_vEncounterID    in varchar2,
                                      pi_vFirstName      in varchar2,
                                      pi_vMI             in varchar2,
                                      pi_vLastName       in varchar2,
                                      pi_vSponsorSSN     in varchar2,
                                      pi_vSSN            in varchar2,
                                      pi_vGender         in varchar2,
                                      pi_vDateOfBirth    in varchar2,
                                      pi_vProviderID     in varchar2,
                                      pi_vAddress1       in varchar2,
                                      pi_vAddress2       in varchar2,
                                      pi_vCity           in varchar2,
                                      pi_vPostal_Code    in varchar2,
                                      pi_vHomePhone      in varchar2,
                                      pi_vCellPhone      in varchar2,
                                      pi_vWorkPhone      in varchar2,
                                      pi_vEmail          in varchar2,
                                      pi_vStateID        in varchar2,
                                      pi_nCellPhoneMsg   in number,
                                      pi_nEmailMsg       in number,
                                      pi_nCallPreference in number,
                                      po_nStatusCode     out number,
                                      po_vStatusComment  out varchar2);

  procedure UpdatePatientDemographics(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      pi_vKey             in varchar2,
                                      pi_vPatientID       in varchar2,
                                      pi_vFirstName       in varchar2,
                                      pi_vMI              in varchar2,
                                      pi_vLastName        in varchar2,
                                      pi_vSponsorSSN      in varchar2,
                                      pi_vSSN             in varchar2,
                                      pi_vGender          in varchar2,
                                      pi_vDateOfBirth     in varchar2,
                                      pi_vProviderID      in varchar2,
                                      pi_vAddress1        in varchar2,
                                      pi_vAddress2        in varchar2,
                                      pi_vCity            in varchar2,
                                      pi_vPostal_Code     in varchar2,
                                      pi_vHomePhone       in varchar2,
                                      pi_vCellPhone       in varchar2,
                                      pi_vWorkPhone       in varchar2,
                                      pi_vEmail           in varchar2,
                                      pi_vStateID         in varchar2,
                                      pi_nCellPhoneMsg    in number,
                                      pi_nEmailMsg        in number,
                                      pi_nCallPreference  in number,
                                      pi_nPrefLangID      in number,
                                      pi_vPrefLangOther   in varchar2,
                                      pi_nDutyStatusID    in number,
                                      pi_nHandPrefID      in number,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2);

  procedure GetPatientTreatmentIdRS(pi_vSessionID       in varchar2,
                                    pi_vSessionClientIP in varchar2,
                                    pi_nUserID          in number,
                                    pi_vPatientID       in varchar2,
                                    po_nStatusCode      out number,
                                    po_vStatusComment   out varchar2,
                                    rs                  out RetRefCursor);

  procedure DelIncPatIntakeAssessments(pi_vSessionID       in varchar2,
                                       pi_vSessionClientIP in varchar2,
                                       pi_nUserID          in number,
                                       pi_vPatientID       in varchar2,
                                       po_nStatusCode      out number,
                                       po_vStatusComment   out varchar2);

  procedure IncPatIntakeAssessments(pi_vSessionID            in varchar2,
                                    pi_vSessionClientIP      in varchar2,
                                    pi_nUserID               in number,
                                    pi_vPatientID            in varchar2,
                                    po_nHasIncPatAssessments out number,
                                    po_nStatusCode           out number,
                                    po_vStatusComment        out varchar2); 

  procedure DeletePatientAssignedModule(pi_vPatientID     in varchar2,
                                        nMID              in number,
                                        po_nStatusCode    out number,
                                        po_vStatusComment out varchar2);    

  --gets dataset to populate Patient Portal Lookup List
  procedure GetPatientPortalListRS(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vKey             in varchar2,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2,
                                   rs                  out Pck_Utl_Common.refCursor);

  procedure updatePatFxUserRights;

  procedure GetPatientSocioeconomicsRS(pi_vSessionID       in varchar2,
                                       pi_vSessionClientIP in varchar2,
                                       pi_nUserID          in number,
                                       pi_vKey             in varchar2,
                                       pi_vPatientID       in varchar2,
                                       po_nStatusCode      out number,
                                       po_vStatusComment   out varchar2,
                                       rs                  out RetRefCursor);

  procedure UpdatePatientSocioeconomics(pi_vSessionID             in varchar2,
                                        pi_vSessionClientIP       in varchar2,
                                        pi_nUserID                in number,
                                        pi_vKey                   in varchar2,
                                        pi_vPatientID             in varchar2,
                                        pi_nHighestGradeID        in number,
                                        pi_nHighestDegreeID       in number,
                                        pi_nMaritalStatusID       in number,
                                        pi_nEmploymentStatusID    in number,
                                        pi_nJobClassificationID   in number,
                                        pi_vEmploymentStatusOther in varchar2,
                                        po_nStatusCode            out number,
                                        po_vStatusComment         out varchar2);

  procedure InsertPatientSocioeconomics(pi_vSessionID             in varchar2,
                                        pi_vSessionClientIP       in varchar2,
                                        pi_nUserID                in number,
                                        pi_vKey                   in varchar2,
                                        pi_vPatientID             in varchar2,
                                        pi_nHighestGradeID        in number,
                                        pi_nHighestDegreeID       in number,
                                        pi_nMaritalStatusID       in number,
                                        pi_nEmploymentStatusID    in number,
                                        pi_nJobClassificationID   in number,
                                        pi_vEmploymentStatusOther in varchar2,
                                        po_nStatusCode            out number,
                                        po_vStatusComment         out varchar2);

end;
/

prompt
prompt Creating package PCK_PATIENT_EVENTS
prompt ===================================
prompt
create or replace package tbicds.PCK_PATIENT_EVENTS
AUTHID CURRENT_USER
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --return recordsets
  type RetRefCursor is ref cursor;

  procedure GetPatientEventsRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vPatientID       in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor);

  procedure GetAllPatientEventsRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor);

  procedure CheckPatMessagesPrefs(pi_vKey       in varchar2,
                                  pi_vPatientID in varchar2,
                                  po_nTextMsg   out number,
                                  po_nEmail     out number);

  procedure SendInternalNotification(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     
                                     pi_vKey       in varchar2,
                                     pi_vPatientID in varchar2,
                                     pi_nEventID   in number,
                                     
                                     po_nStatusCode    out number,
                                     po_vStatusComment out varchar2);

  procedure CompletedEvent(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           
                           pi_vKey       in varchar2,
                           pi_vPatientID in varchar2,
                           pi_nEventID   in number,
                           
                           po_nStatusCode    out number,
                           po_vStatusComment out varchar2);

  procedure AddAllEvents(pi_vSessionID       in varchar2,
                         pi_vSessionClientIP in varchar2,
                         pi_nUserID          in number,
                         
                         pi_vPatientID in varchar2,
                         
                         po_nStatusCode    out number,
                         po_vStatusComment out varchar2);

  procedure UpdatePatientEvent(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               
                               pi_vKey       in varchar2,
                               pi_vPatientID in varchar2,
                               pi_nEventID   in number,
                               pi_vEventDate in varchar2,
                               pi_nStatus    in number,
                               pi_vComments  in varchar2,
                               
                               po_nStatusCode    out number,
                               po_vStatusComment out varchar2);

  procedure SendEventNotification(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  
                                  pi_vKey       in varchar2,
                                  pi_vPatientID in varchar2,
                                  pi_nEventID   in number,
                                  
                                  po_nStatusCode    out number,
                                  po_vStatusComment out varchar2);

  procedure GetStatEventsRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2,
                            rs                  out RetRefCursor);

  procedure AddSpecificEvent(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vPatientID       in varchar2,
                             pi_nEventID         in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2);

  procedure CompletedSpecificEvent(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vKey             in varchar2,
                                   pi_vPatientID       in varchar2,
                                   pi_nEventID         in number,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2);

  procedure AssignModuleGroupEvent(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   
                                   pi_vPatientID  in varchar2,
                                   pi_nEventID    in number,
                                   pi_dtEventDate in date,
                                   
                                   po_nStatusCode    out number,
                                   po_vStatusComment out varchar2);

  procedure SendPatEventReminder(pi_vKey           in varchar2,
                                 po_nStatusCode    out number,
                                 po_vStatusComment out varchar2);

  procedure SendInternalReminder(pi_vKey           in varchar2,
                                 pi_vPatientID     in varchar2,
                                 pi_nEventID       in number,
                                 po_nStatusCode    out number,
                                 po_vStatusComment out varchar2);

  procedure SendEventReminder(pi_vKey           in varchar2,
                              pi_vPatientID     in varchar2,
                              pi_nEventID       in number,
                              po_nStatusCode    out number,
                              po_vStatusComment out varchar2);

  procedure GetPatByEvtDueDateRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 
                                 pi_vKey   in varchar2,
                                 pi_vDate1 in varchar2,
                                 pi_vDate2 in varchar2,
                                 
                                 po_nStatusCode    out number,
                                 po_vStatusComment out varchar2,
                                 rs                out RetRefCursor);

  procedure GetPatByOverdueEvtRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_vKey             in varchar2,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor);

  procedure GetAllPatientsListRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_vKey             in varchar2,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out Pck_Utl_Common.refCursor);

  function IsEventDateReadOnly(pi_vPatientID in varchar2,
                               pi_nEventID   in number) return number;

  procedure CheckPAPEventALL(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             
                             pi_vKey in varchar2,
                             
                             po_nStatusCode    out number,
                             po_vStatusComment out varchar2);

  procedure CheckPAPEvent(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          
                          pi_vKey       in varchar2,
                          pi_vPatientID in varchar2,
                          
                          po_nStatusCode    out number,
                          po_vStatusComment out varchar2);

  function UpdateStatusDate(pi_vPatientID in varchar2,
                            pi_nEventID   in number,
                            pi_nStatus    in number,
                            pi_vEventDate in varchar2) return number;

  -- Get JSON string of patient events
  procedure GetAllPatEventsJSONRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  pi_vKey             in varchar2,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor);

end;
/

prompt
prompt Creating package PCK_PATIENT_LOCK
prompt =================================
prompt
create or replace package tbicds.PCK_PATIENT_LOCK
AUTHID CURRENT_USER
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --custom to return recordsets
  type RetRefCursor is ref cursor;

  procedure GetPatientLock(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_vPatientID       in varchar2,
                           rs                  out RetRefCursor,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2);

  procedure InsertPatientLock(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vPatientID       in varchar2,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2);

  procedure DeletePatientLock(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vPatientID       in varchar2,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2);

  procedure RefreshPatientLock(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vPatientID       in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2);

end;
/

prompt
prompt Creating package PCK_PATIENT_TX_STEP
prompt ====================================
prompt
create or replace package tbicds.PCK_PATIENT_TX_STEP
AUTHID CURRENT_USER
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  type RetRefCursor is ref cursor;

  procedure InsertPatientStep(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              
                              pi_vPatientID in varchar2,
                              pi_nStep      in number,
                              
                              po_nStatusCode    out number,
                              po_vStatusComment out varchar2);

  procedure UpdatePatientSteps(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               
                               pi_vPatientID in varchar2,
                               
                               po_nStatusCode    out number,
                               po_vStatusComment out varchar2);

  procedure DeletePatientStep(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              
                              pi_vPatientID in varchar2,
                              pi_nStep      in number,
                              
                              po_nStatusCode    out number,
                              po_vStatusComment out varchar2);

  procedure GetPatientStepRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             
                             pi_vPatientID in varchar2,
                             
                             po_nStatusCode    out number,
                             po_vStatusComment out varchar2,
                             rs                out RetRefCursor);

  procedure UpdateNotificationStep(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   
                                   pi_vPatientID        in varchar2,
                                   pi_nNotificationStep in number,
                                   
                                   po_nStatusCode    out number,
                                   po_vStatusComment out varchar2);

end;
/

prompt
prompt Creating package PCK_PAT_ETHNICITY_RACE
prompt =======================================
prompt
create or replace package tbicds.PCK_PAT_ETHNICITY_RACE AUTHID CURRENT_USER is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  -- custom to return recordsets
  type RetRefCursor is ref cursor;

  procedure InsertPatientEthnicity(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID       in varchar2,
                                   pi_nEthnicityID     in number,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2);

  procedure InsertPatientRace(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vPatientID       in varchar2,
                              pi_nRaceID          in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2);

  procedure InsertPatEthRaceSource(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID       in varchar2,
                                   pi_nSourceID        in number,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2);

  procedure GetEthnicityRS(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out RetRefCursor);

  procedure GetRaceRS(pi_vSessionID       in varchar2,
                      pi_vSessionClientIP in varchar2,
                      pi_nUserID          in number,
                      po_nStatusCode      out number,
                      po_vStatusComment   out varchar2,
                      rs                  out RetRefCursor);

  procedure GetEthRaceSourceRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor);

  procedure GetPatientEthnicityRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  pi_vPatientID       in varchar2,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor);

  procedure GetPatientRaceRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vPatientID       in varchar2,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor);

  function GetPatientRaceListString(pi_vPatientID in varchar2)
    return varchar2;

  procedure GetPatEthRaceSourceRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  pi_vPatientID       in varchar2,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor);

  procedure DeletePatientEthnicity(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID       in varchar2,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2);

  procedure DeletePatientRace(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vPatientID       in varchar2,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2);

  procedure DeletePatEthRaceSource(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID       in varchar2,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2);

  procedure UpdatePatientRace(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              
                              pi_vPatientID in varchar2,
                              pi_vValues    in varchar2,
                              
                              po_nStatusCode    out number,
                              po_vStatusComment out varchar2);

  procedure UpdatePatientEthnicity(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID       in varchar2,
                                   pi_nEthnicityID     in number,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2);

end;
/

prompt
prompt Creating package PCK_PAT_TREATMENT
prompt ==================================
prompt
create or replace package tbicds.PCK_PAT_TREATMENT
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 --type defs to return recordsets
  type RetRefCursor is ref cursor;
  type refCursor is ref cursor;

/*delete a treatment program*/
procedure DeleteTreatmentProgram( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                                
                           pi_nRegionID            in number,
                           pi_nSiteID              in number,
                           pi_vPatientID           in varchar2,
                           pi_nProgramID          in number,
                          
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          );
                          
/*delete a treatment*/
procedure DeleteTreatment( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                                
                           pi_nRegionID            in number,
                           pi_nSiteID              in number,
                           pi_vPatientID           in varchar2,
                           pi_nTreatmentID         in number,
                          
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          );
                          
/*get treatment program rs by program id*/
procedure GetTreatmentProgramRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nTreatmentID           in long,
      pi_nProgramID             in long,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*update patient treatment program record*/
procedure UpdateTreatmentProgram( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                           pi_vPatientID           in varchar2,
                           pi_nTreatmentID         in number,
                           pi_nProgramID           in number,
                           
                           pi_nCPAID               in number, 
                           pi_dtInitialDate        in date,
                           pi_dtEndDate            in date,
                                
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          );
                          
/*update patient treatment record*/
procedure UpdateTreatment( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                           pi_vPatientID           in varchar2,
                           pi_nTreatmentID         in number,
                           
                           pi_nTreatmentType       in number, 
                           pi_vTreatmentTitle      in varchar2,
                           
                           pi_dtInitialDate        in date,
                           pi_dtEndDate            in date,
                                
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          );
/*get treatment rs by id*/
procedure GetTreatmentRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nTreatmentID           in long,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*get treatment program rs*/
procedure GetTreatmentProgramRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nTreatmentID           in long,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );

/*
gets a recordset of all treatments for this patient
*/
procedure GetTreatmentRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
        
  
/*
insert a new patient treatment
*/
procedure InsertTreatment( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                                
                           pi_nRegionID            in number,
                           pi_nSiteID              in number,
                           pi_vPatientID           in varchar2,
                          
                           pi_nTreatmentTypeID     in number,
                           pi_dtInitialDate        in date,
                           pi_dtEndDate            in date,
                           pi_vTreatmentTitle      in varchar2,
                                
                           po_nPatTreatmentID     out number,
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          );
                          

/*
insert a new patient treatment program
*/
procedure InsertTreatmentProgram( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                                
                           pi_nRegionID            in number,
                           pi_nSiteID              in number,
                           
                           pi_vPatientID           in varchar2,
                           pi_nPatTreatmentID      in number,
                           pi_nCPAID               in number,
                                                      
                           pi_dtInitialDate        in date,
                           pi_dtEndDate            in date,
                          
                           po_nPatTreatProgID     out number,
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          );


end PCK_PAT_TREATMENT;
/

prompt
prompt Creating package PCK_PROVIDER
prompt =============================
prompt
create or replace package tbicds.PCK_PROVIDER
AUTHID CURRENT_USER
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --recordsets
  type RetRefCursor is ref cursor;

  procedure GetProviderRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vDIMSID          in varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor);

end;
/

prompt
prompt Creating package PCK_PWEVENT
prompt ============================
prompt
create or replace package tbicds.PCK_PWEVENT
AUTHID CURRENT_USER 
is
  /* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --type defs to return recordsets
  type RetRefCursor is ref cursor;
  type refCursor is ref cursor;
 
  --constants
  c_nSUBJECTIVE  constant number := 1;
  c_nOBJECTIVE   constant number := 2;
  c_nASSESSMENT  constant number := 3;
  c_nPLAN        constant number := 4;
  c_nREVIEW      constant number := 5;
  c_nOTHER       constant number := 6;
   
  c_nBETTER      constant number := 1;
  c_nSAME        constant number := 2;
  c_nWORSE       constant number := 3;

/*gets recent clinics used for events*/
procedure GetRecentClinicRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*gets recent note titles used for events*/
procedure GetRecentNoteTitleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/***
insert modules into the pat pw event module 
****/
procedure InsertPatPWEventModule (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      pi_nMID                   in number,
      
      po_nEventModuleID         out number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
procedure InsertPatPWEvent (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
   
      pi_vEventTitle            in varchar2,
      pi_dtEventDate            in date,
      
      po_nPatPWEventID          out number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
/*****
Gets todays pathway events associated with a patient
******/
procedure GetTodaysPatPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*gets the no pathway for a patient*/
procedure GetNoPathwayRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*gets all open encounters for a patient*/
procedure GetOpenEncountersRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
       
/*updates the intrument date*/
procedure UpdateInstrumentDate (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nIntakeID              in number,
      pi_dtDate                 in date,
                      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
/*get the most recent medical history record*/
procedure GetMedicalHxRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*insert a new medical history record*/
procedure InsertMedicalHx ( pi_vSessionID           in varchar2,
                            pi_vSessionClientIP     in varchar2,
                            pi_nUserID              in number,
                                
                            pi_nRegionID            in number,
                            pi_nSiteID              in number,
                            pi_vPatientID           in varchar2,
                            pi_nPatPWID             in number,
                            pi_nPatPWEventID        in number,
                            
                            po_nStatusCode           out number,
                            po_vStatusComment        out varchar2
                          );
                          
/*get the most recent medical history intake_id*/ 
procedure GetMedicalHxIntakeID(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,   
                               pi_vPatientID       in varchar2,
                               po_nIntakeID        out number,   
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2);
                          
/*save note progress, used while the note is being written but before 
it is commited*/
procedure SaveNoteProgress (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      
      pi_nEncounterType         in number,
      pi_vNoteTitle             in varchar2,
      pi_vLocation              in varchar2,
      pi_vCosigner              in varchar2,
      pi_vConsult               in varchar2,
      pi_vNote                  in clob,
                      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );


/*write note details to tbi cds after commited to MDWS*/
procedure WriteNote (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      
      pi_vDFN                   in varchar2,
      pi_vDUZ                   in varchar2,
      pi_vEncounterID           in varchar2,
      pi_vConsultIEN            in varchar2,
      pi_vCosignerDUZ           in varchar2,
      pi_vNoteTitleIEN          in varchar2,
      pi_vTIUNoteID             in varchar2,
      pi_vTIUNote               in clob,
      pi_nClinicID              in number,
      pi_nEncounterType         in number,
      pi_vNoteTitle             in varchar2,
      pi_vLocation              in varchar2,
      pi_vCosigner              in varchar2,
      pi_vConsult               in varchar2,
      pi_vTBINote               in clob,
                      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
 /******
 get list of event entry types Subjective, Objective, Assessment, Plan etc...
 ******/ 
 procedure GetEventEntryTypeRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
 /***
 Gets the previous score value for a mid
 ***/ 
 function GetPrevIntakeScore(pi_nMID in number,
                            pi_vPatientID in varchar2,
                            pi_nIntakeID in number)
  
 return number;
 
 /***
 Gets the previous score value for the subscale of a mid
 ***/
 function GetPrevIntakeSubscaleScore(pi_nMID in number,
                                     pi_vPatientID in varchar2,
                                     pi_nIntakeID in number,
                                     pi_nSeries in number)
 return number;             
 
 /***
 Gets the next event id after the event past in
 ***/
 function GetNextPatPWEventID(pi_nPatPWEventID in number,
                             pi_vPatientID in varchar2)
  
 return number;
 

 
 /*inserts a new pathway event*/
procedure InsertPWEvent ( pi_vSessionID           in varchar2,
                          pi_vSessionClientIP     in varchar2,
                          pi_nUserID              in number,
                                
                          pi_nRegionID            in number,
                          pi_nSiteID              in number,
                          pi_vPatientID           in varchar2,
                          pi_nPatPWID             in number,
                          pi_vEventTitle          in varchar2,
                          pi_dtEventDate          in varchar2,
                          pi_nRelatedEventID      in number,
                                
                          po_nPatPWEventID           out number,
                          po_nStatusCode           out number,
                          po_vStatusComment        out varchar2
                          );
                           
  /******
  insert an event entry 
  ******/  
  procedure InsertPWEventEntry (  pi_vSessionID             in varchar2,
                                  pi_vSessionClientIP       in varchar2,
                                  pi_nUserID                in number,
                                
                                  pi_vPatientID             in varchar2,
                                  pi_nPatPWEventID          in number,
                                  pi_nPWEventModuleID       in number,
                                  pi_nEventEntryTypeID      in number,
                                  pi_dtEventDate            in date,
                                  pi_vEventEntryComment     in varchar2,
                                  pi_nEventStatusID         in number,
                                  pi_nEventSeverityID       in number,
                                
                                  po_nEventEntryID          out number,
                                
                                  po_nStatusCode           out number,
                                  po_vStatusComment        out varchar2
                               );
                               
  /******
  update an event entry 
  ******/  
  procedure UpdatePWEventEntry (  pi_vSessionID             in varchar2,
                                  pi_vSessionClientIP       in varchar2,
                                  pi_nUserID                in number,
                                
                                  pi_nEventEntryID          in number,
                                  pi_nPWEventModuleID       in number,
                                  pi_dtEventDate            in date,
                                  pi_vEventEntryComment     in varchar2,
                                  pi_nEventStatusID         in number,
                                  pi_nEventSeverityID       in number,
                             
                                  po_nStatusCode           out number,
                                  po_vStatusComment        out varchar2
                               );
  
  /*
update the plan portion of the event
*/
procedure UpdatePWEventPlan (  pi_vSessionID             in varchar2,
                               pi_vSessionClientIP       in varchar2,
                               pi_nUserID                in number,
                               
                               pi_nPatPWEventID          in number,
                               pi_nPatPWPlanEventID      in number,
                               pi_vPlanText              in clob,
                               
                               po_nStatusCode           out number,
                               po_vStatusComment        out varchar2
                             );
                             
  /***
  delete entry
  ***/
  procedure DeletePWEventEntry (  pi_vSessionID             in varchar2,
                                  pi_vSessionClientIP       in varchar2,
                                  pi_nUserID                in number,
                                 
                                  pi_nEventEntryID          in number,
                                  po_nStatusCode           out number,
                                  po_vStatusComment        out varchar2
                               );
                                                        
  /******
  get list of event statuses Better, Same, Worse etc...
  ******/  
  procedure GetEventStatusRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
  /******
  get list of event severities
  ******/  
  procedure GetEventSeverityRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
  /******
  get list of event entries for an event
  ******/ 
  procedure GetEventEntryRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
  /***
  Get all outcome measures associated with this event
  ***/
  procedure GetOutcomeMeasuresRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
   /***
   Get all scores for an intake
   ***/
   procedure GetIntakeScoreRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nIntakeID              in number,
      pi_nMID                   in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
    /*****
    Gets next pathway event associated with a patient
    ******/
    procedure GetNextPatPWEventRS (
          pi_vSessionID             in varchar2,
          pi_vSessionClientIP       in varchar2,
          pi_nUserID                in number,
          pi_vPatientID             in varchar2,
          pi_nPatPWEventID          in number,
          po_nStatusCode            out number,
          po_vStatusComment         out varchar2,
          rs                        out RetRefCursor
          );

end PCK_PWEVENT;
/

prompt
prompt Creating package PCK_QUESTIONNAIRES
prompt ===================================
prompt
create or replace package tbicds.PCK_QUESTIONNAIRES
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  type RetRefCursor is ref cursor;

  procedure GetModuleRS(pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        pi_nMID             in number,
                        po_nStatusCode      out number,
                        po_vStatusComment   out varchar2,
                        rs                  out RetRefCursor);

  procedure GetModuleTopicRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_nMID             in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor);

  procedure GetQuestionRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_nMID             in number,
                          pi_nTID             in number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor);

  procedure GetResponseRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_nMID             in number,
                          pi_nTID             in number,
                          pi_nQID             in number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor);

  procedure GetSkipPatternRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_nMID             in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor);

  procedure GetMaskRS(pi_vSessionID       in varchar2,
                      pi_vSessionClientIP in varchar2,
                      pi_nUserID          in number,
                      pi_nMID             in number,
                      po_nStatusCode      out number,
                      po_vStatusComment   out varchar2,
                      rs                  out RetRefCursor);

  procedure GetStatData(pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        pi_nMID             in number,
                        pi_nTID             in number,
                        pi_nQID             in number,
                        pi_nRID             in number,
                        po_nStatusCode      out number,
                        po_vStatusComment   out varchar2,
                        rs                  out RetRefCursor);
                        
  procedure GetNextModuleRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vPatientID       in varchar2,
                          pi_vSiteID          in varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor);
                          
  /* gets a new intake_id for the module */
  procedure GetNewIntakeID(pi_vSessionID       in varchar2,
                      pi_vSessionClientIP in varchar2,
                      pi_nUserID          in number,
                      po_nStatusCode      out number,
                      po_vStatusComment   out varchar2,
                      rs                  out RetRefCursor);

end PCK_QUESTIONNAIRES;
/

prompt
prompt Creating package PCK_REFERRAL_CLINIC
prompt ====================================
prompt
create or replace package tbicds.PCK_REFERRAL_CLINIC
AUTHID CURRENT_USER
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  type RetRefCursor is ref cursor;

  procedure GetReferralClinicRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nStatReferralID  in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor);

  procedure GetReferralClinicLookUpRS(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2,
                                      rs                  out RetRefCursor);

  procedure InsertReferralClinic(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_vReferralDesc    in varchar2,
                                 pi_vReferralText    in varchar2,
                                 pi_vProviderName in varchar2,
                                 pi_vAddress      in varchar2,
                                 pi_vCity         in varchar2,
                                 pi_nStateID      in number,
                                 pi_vPostalCode   in varchar2,
                                 pi_vPhone        in varchar2,
                                 pi_vFax          in varchar2,
                                 po_nReferralID    out number,
                                 po_nStatusCode    out number,
                                 po_vStatusComment out varchar2);

  procedure UpdateReferralClinic(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_nReferralID      in number,
                                 pi_vReferralDesc    in varchar2,
                                 pi_vReferralText    in varchar2,
                                 pi_vProviderName in varchar2,
                                 pi_vAddress      in varchar2,
                                 pi_vCity         in varchar2,
                                 pi_nStateID      in number,
                                 pi_vPostalCode   in varchar2,
                                 pi_vPhone        in varchar2,
                                 pi_vFax          in varchar2,
                                 po_nStatusCode    out number,
                                 po_vStatusComment out varchar2);

  procedure DiscontinueReferralClinic(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      pi_nReferralID      in number,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2);

end;
/

prompt
prompt Creating package PCK_REGION_SITE
prompt ================================
prompt
CREATE OR REPLACE PACKAGE TBICDS.PCK_REGION_SITE
AUTHID CURRENT_USER 
IS
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 
--custom to return recordsets
type RetRefCursor is ref cursor;
type refCursor is ref cursor;

procedure GetRegionRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out refCursor
      );

procedure GetSiteRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nRegionID              in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out refCursor
      );
      
procedure GetSiteRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vSRV                   in varchar2,
      pi_vPORT                  in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out refCursor
      );

procedure GetSiteRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out refCursor
      );
END;
/

prompt
prompt Creating package PCK_REPORTS
prompt ============================
prompt
create or replace package tbicds.PCK_REPORTS
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 --type defs to return recordsets
  type RetRefCursor is ref cursor;
  type refCursor is ref cursor;
 
  --constants
  c_nSUBJECTIVE  constant number := 1;
  c_nOBJECTIVE   constant number := 2;
  c_nASSESSMENT  constant number := 3;
  c_nPLAN        constant number := 4;
  c_nREVIEW      constant number := 5;
  c_nOTHER       constant number := 6;
   
  c_nBETTER      constant number := 1;
  c_nSAME        constant number := 2;
  c_nWORSE       constant number := 3;

/*loads a temp table with population matching criteria*/  
procedure LoadPopulation (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_dtFrom                 in date,      
      pi_dtTo                   in date,
      pi_nClinicalSetting       in number,
     
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_nCPAID                 in number,
      
      pi_nImpairmentID          in number,
      pi_nInjuryID              in number,
      pi_nGender                in number,
      pi_nMilStatusID           in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
  /*get rs of injuries*/
procedure GetInjuryRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*get rs of impairments*/
  procedure GetImpairmentRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
  
  /*get aggregate report given the module group id and mid*/
  procedure GetAggReportRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nModuleGroupID         in number,
      pi_nMID                   in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );

function GetImpairmentRID(pi_vPatientID in varchar2,
                          pi_dtEnd in date) return number;

function GetInjuryRID(pi_vPatientID in varchar2,
                          pi_dtEnd in date) return number;
                          
/*gets the admission intake id*/
function GetAdmissionIntakeID(pi_nMID in number,
                              pi_vPatientID in varchar2,
                              pi_dtStart in date,
                              pi_dtEnd in date)  return number;

/*get the discharge intake id*/                              
function GetDischargeIntakeID(pi_nMID in number,
                              pi_vPatientID in varchar2,
                              pi_dtStart in date,
                              pi_dtEnd in date)  return number;

/*get the followup instrument id*/                              
function GetFollowupIntakeID(pi_nMID in number,
                             pi_vPatientID in varchar2,
                             pi_nDischargeID in number) return number;                              
      

end PCK_REPORTS;
/

prompt
prompt Creating package PCK_REPORTS_AGG
prompt ================================
prompt
create or replace package tbicds.PCK_REPORTS_AGG
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --type defs to return recordsets
  type RetRefCursor is ref cursor;
  type refCursor is ref cursor;
  
  
  
end PCK_REPORTS_AGG;
/

prompt
prompt Creating package PCK_REPORTS_PAT
prompt ================================
prompt
create or replace package tbicds.PCK_REPORTS_PAT
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 type RetRefCursor is ref cursor;


 procedure GetTrendBaseRS( pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_vPatientID       in varchar2,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out RetRefCursor);
                           
function GetPrevIntakeScore(pi_nMID in number,
                            pi_vPatientID in varchar2,
                            pi_nIntakeID in number)
  
 return number;
 
function GetCurrentIntakeScore(pi_vPatientID in varchar2,
                               pi_nMID in number)
  
 return number;
 
procedure GetNoteDatesRS( pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vPatientID       in varchar2,
                          pi_dtFrom           in date,
                          pi_dtTo             in date,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor);
                          
procedure GetNoteTextRS( pi_vSessionID       in varchar2,
                         pi_vSessionClientIP in varchar2,
                         pi_nUserID          in number,
                         pi_vPatientID       in varchar2,
                         pi_nPatPWEventID    in number,
                         pi_dtFrom           in date,
                         pi_dtTo             in date,
                         po_nStatusCode      out number,
                         po_vStatusComment   out varchar2,
                         rs                  out RetRefCursor);
                          
procedure GetInstrumentScoreRS( pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vPatientID       in varchar2,
                                pi_nMID             in number,
                                pi_dtFrom           in date,
                                pi_dtTo             in date,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor); 
                                
/*gets all scorable modules for this patient and date range
with the 10 most recent columns nulled out for fill in later*/
procedure GetInstrumentsBaseRS( pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vPatientID       in varchar2,
                                pi_dtFrom           in date,
                                pi_dtTo             in date,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor);
                                
 procedure GetPatPopulationRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vKey             in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor); 
  

end PCK_REPORTS_PAT;
/

prompt
prompt Creating package PCK_REPORTS_PI
prompt ===============================
prompt
create or replace package tbicds.PCK_REPORTS_PI
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
--type defs to return recordsets
  type RetRefCursor is ref cursor;
  type refCursor is ref cursor;

procedure GetPopScoreAvgALLRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nExcludeSiteID         in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
procedure GetPopModuleSeriesRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
    
      pi_nSiteID                in number,
      pi_nMID                   in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*gets population scores*/
procedure GetPopScoreRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vKey                   in varchar2,
  
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );

procedure GetPopScoreAvgRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
procedure GetPopModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vKey                   in varchar2,
   
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
procedure GetPopSiteIDRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
     
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );

procedure GetPopMIDRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
     
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      );
      
/*load the population module table*/
procedure LoadPopModule (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nMID                   in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
/*loads a temp table with population matching criteria*/
procedure LoadPopulation (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vKey                   in varchar2,
   
      
      pi_dtFrom                 in date,      
      pi_dtTo                   in date,
      pi_nClinicalSetting       in number,
     
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_nCPATypeID             in number, --type
      
      pi_nImpairmentID          in number,
      pi_nInjuryID              in number,
      pi_vGender                in varchar2,
      pi_nMilStatusID           in number,
      pi_vSiteIDS               in varchar2,
  
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      );
      
end PCK_REPORTS_PI;
/

prompt
prompt Creating package PCK_REPORTS_STAT
prompt =================================
prompt
create or replace package tbicds.PCK_REPORTS_STAT
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 --type defs to return recordsets
  type RetRefCursor is ref cursor;
  type refCursor is ref cursor;

  procedure CreateExportRequestRS(pi_vSessionID         in varchar2,
                                  pi_vSessionClientIP   in varchar2,
                                  pi_nUserID            in number,
                                  pi_vExportRequestName in varchar2,
                                  po_nStatusCode        out number,
                                  po_vStatusComment     out varchar2,
                                  rs                    out RetRefCursor);

  procedure GetMyRequestRS(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out RetRefCursor);

  procedure RenameExportRequest(pi_vSessionID            in varchar2,
                                pi_vSessionClientIP      in varchar2,
                                pi_nUserID               in number,
                                pi_nRequestID            in number,
                                pi_vNewExportRequestName in varchar2,
                                po_nStatusCode           out number,
                                po_vStatusComment        out varchar2);

  procedure UpdateExportRequest(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nRequestID       in number,
                                pi_vFilters         in varchar2,
                                pi_vDataFields      in varchar2,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2);

  procedure GetExportRequestRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_nRequestID       in number,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor);

  procedure SaveAsExportRequest(pi_vSessionID         in varchar2,
                                pi_vSessionClientIP   in varchar2,
                                pi_nUserID            in number,
                                pi_vExportRequestName in varchar2,
                                pi_vFilters         in varchar2,
                                pi_vDataFields      in varchar2,
                                po_nStatusCode        out number,
                                po_vStatusComment     out varchar2);
                                
  procedure SubmitExportRequest(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vKey             in varchar2,
                                pi_nRequestID       in number,
                                pi_vFilters         in varchar2,
                                pi_vDataFields      in varchar2,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2);
                                
  procedure CancelExportRequest(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nRequestID       in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2);
                                
  procedure GetExportRequestCSVFileRS(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      pi_nRequestID       in number,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2,
                                      rs                  out RetRefCursor);

  procedure SubmitNewExportRequest(pi_vSessionID         in varchar2,
                                   pi_vSessionClientIP   in varchar2,
                                   pi_nUserID            in number,
                                   pi_vKey               in varchar2,
                                   pi_vExportRequestName in varchar2,
                                   pi_vFilters           in varchar2,
                                   pi_vDataFields        in varchar2,
                                   po_nStatusCode        out number,
                                   po_vStatusComment     out varchar2);
                                   
end PCK_REPORTS_STAT;
/

prompt
prompt Creating type TYP_TBL_RPT_CDE_PAT
prompt =================================
prompt
create or replace type tbicds.TYP_TBL_RPT_CDE_PAT is table of TYP_OBJ_RPT_CDE_PAT
/

prompt
prompt Creating package PCK_RPT_CDE
prompt ============================
prompt
create or replace package tbicds.PCK_RPT_CDE
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   -- Public constant declarations
   c_vEncrytedCdeIDs           constant varchar2(256) := 'C00007,C00035';
   c_nShowLatestIntake         constant number(1) := 0;
   c_nIncludeNoIntake          constant number(1) := 0;
   
   -- getPatientCdeValue
   procedure getPatientCdeValue (
      pi_vPatientID                     in varchar2,
      pi_vCdeID                         in varchar2,
      pi_nIntakeID                      in number,
      pi_vKey                           in varchar2,
      po_vValue                        out varchar2
      );

   -- setPatientCde
   procedure setPatientCde (
      pi_vPatientID                     in varchar2 default null
      );

   -- tblPatientCde
   function tblPatientCde (
      pi_vKey                           in varchar2,
      pi_vProviderID                    in varchar2,
      pi_dDateRange_Start               in date,
      pi_dDateRange_End                 in date
      ) return                             typ_tbl_rpt_cde_pat pipelined;

   -- tblPatientCde_Cached: use patient_cde table
   function tblPatientCde_Cached (
      pi_vKey                           in varchar2,
      pi_vProviderID                    in varchar2,
      pi_dDateRange_Start               in date,
      pi_dDateRange_End                 in date
      ) return                             typ_tbl_rpt_cde_pat pipelined;

   -- GetPatientCdeRS
   procedure GetPatientCdeRS (
      pi_vSessionID                     in varchar2,
      pi_vSessionClientIP               in varchar2,
      pi_nUserID                        in number,
      --pi_nReportID                      in number,
      pi_vKey                           in varchar2,
      pi_vProviderID                    in varchar2,
      pi_vDateRange_Start               in varchar2,
      pi_vDateRange_End                 in varchar2,
      po_nStatusCode                   out number,
      po_vStatusComment                out varchar2,
      rs                               out sys_refcursor
      );

   -- GetPatientCdeRS_Cached
   procedure GetPatientCdeRS_Cached (
      pi_vSessionID                     in varchar2,
      pi_vSessionClientIP               in varchar2,
      pi_nUserID                        in number,
      --pi_nReportID                      in number,
      pi_vKey                           in varchar2,
      pi_vProviderID                    in varchar2,
      pi_vDateRange_Start               in varchar2,
      pi_vDateRange_End                 in varchar2,
      po_nStatusCode                   out number,
      po_vStatusComment                out varchar2,
      rs                               out sys_refcursor
      );

end;
/

prompt
prompt Creating package PCK_STAT
prompt =========================
prompt
create or replace package tbicds.PCK_STAT
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  type RetRefCursor is ref cursor;

  procedure GetDataCollectionRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vDataCollection  in varchar2,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor);

end PCK_STAT;
/

prompt
prompt Creating package PCK_SYSTEM_ID
prompt ==============================
prompt
create or replace package tbicds.PCK_SYSTEM_ID
AUTHID CURRENT_USER 
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --id type prefixes 
  c_vPatient    varchar2(3) := 'PAT';
  c_vProvider   varchar2(3) := 'PRO';
  c_vContact    varchar2(3) := 'CON';
  c_vEncounter  varchar2(3) := 'ENC';
  c_vProblem    varchar2(4) := 'PROB';
  c_vProbObserv varchar2(4) := 'OBSV';
  c_vLab        varchar2(4) := 'LAB';
  c_vLabResult  varchar2(4) := 'LRES';
  c_vCDA        varchar2(4) := 'CDA';

  c_vVS             varchar2(4) := 'VITS';
  c_vVSOrganizer    varchar2(6) := 'VSORG';
  c_vVSObservation  varchar2(6) := 'VSOBSV';
  c_vVSObsComponent varchar2(7) := 'VSOCOMP';
  c_vPatSource      varchar2(6) := 'PATSRC';

  function GetNewPersonID return varchar2;

  function GetNewPatientID(pi_vFirstName   in varchar2,
                           pi_vLastName    in varchar2,
                           pi_vDateOfBirth in varchar2,
                           pi_vGender      in varchar2,
                           pi_vSSN         in varchar2) return varchar2;

  function GetNewProviderID(pi_vFirstName   in varchar2,
                            pi_vLastName    in varchar2) return varchar2;

  function GetNewProviderID(pi_vFirstName in varchar2,
                            pi_vLastName  in varchar2,
                            pi_vNPI       in varchar2) return varchar2;

  function GetNewContactPatientID(pi_vPatientID in varchar2) return varchar2;

  function FromStringToNumber(pi_vString in varchar2, pi_nLength in number)
    return varchar2;

  function FromNumberToString(pi_vNumber in varchar2) return varchar2;

  function GenerateRandomString(pi_nLength in number) return varchar2;

  function GetDateTimeString return varchar2;

end;
/

prompt
prompt Creating package PCK_SYSTEM_SETTINGS
prompt ====================================
prompt
create or replace package tbicds.PCK_SYSTEM_SETTINGS
AUTHID CURRENT_USER
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  type RetRefCursor is ref cursor;

  procedure GetSiteRS(pi_vSessionID       in varchar2,
                      pi_vSessionClientIP in varchar2,
                      pi_nUserID          in number,
                      po_nStatusCode      out number,
                      po_vStatusComment   out varchar2,
                      rs                  out RetRefCursor);                        

end;
/

prompt
prompt Creating package PCK_TEMPLATE
prompt =============================
prompt
create or replace package tbicds.PCK_TEMPLATE
AUTHID CURRENT_USER
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --custom to return recordsets
  type RetRefCursor is ref cursor;
  type refCursor is ref cursor;

  procedure InsertTemplate(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_nSOAPsectID      in number,
                           pi_vTemplateName    in varchar2,
                           pi_vTemplateText    in clob,
                           pi_nTempGroupID     in number,
                           po_nTemplateID      out number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2);

  procedure UpdateTemplate(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_nTemplateID      in number,
                           pi_nGroupID         in number,
                           pi_vTemplateName    in varchar2,
                           pi_vTemplateText    in clob,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2);
                                 
  procedure GetParsedTemplate2RS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_vPatientID       in varchar2,
                                 pi_vEncounterID     in varchar2,
                                 pi_nTemplateID      in number,
                                 pi_vKey             in varchar2,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor);

  procedure GetTemplateDataTagRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor);

  procedure GetTemplateDataTagGroupRS(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2,
                                      rs                  out RetRefCursor);

  procedure GetTemplateTypeRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out RetRefCursor);

  procedure GetTemplateRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor);
                          
  procedure GetTemplateRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_nTypeID          in number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor);

  procedure DiscontinueTemplate(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nTemplateID      in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2);

  procedure InsertTemplateGroup(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vTemplateGrpName in varchar2,
                                pi_vComments        in varchar2,
                                po_nTemplateGrpID   out number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2);

  procedure UpdateTemplateGroup(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nTemplateGrpID   in number,
                                pi_vTemplateGrpName in varchar2,
                                pi_vComments        in varchar2,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2);

  procedure DiscontinueTemplateGroup(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     pi_nTemplateGrpID   in number,
                                     po_nStatusCode      out number,
                                     po_vStatusComment   out varchar2);

  procedure GetTemplateGroupsRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor);

  procedure GetGroupTemplatesRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nGroupID         in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor);

  function fnGetParsedTemplateText(pi_vPatientID    in varchar2,
                                   pi_vKey          in varchar2,
                                   pi_vTemplateText in varchar2) return clob;
                                   
  function fnReplaceClob (pi_source in clob
                         ,pi_search in varchar2
                         ,pi_replace in clob) return clob;                                    

end;
/

prompt
prompt Creating package PCK_USER
prompt =========================
prompt
create or replace package tbicds.PCK_USER
AUTHID CURRENT_USER
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --return recordsets
  type RetRefCursor is ref cursor;

  --get a record set
  procedure GetLoginUserRS (
      pi_vSessionID              in varchar2,
      pi_vSessionClientIP        in varchar2,
      pi_nUserID                 in number,
      pi_vKey in varchar2,
      pi_nFXUserID               in number,
      po_nStatusCode             out number,
      po_vStatusComment          out varchar2,
      rs                         out RetRefCursor
      );

end;
/

prompt
prompt Creating package PCK_USER_ADMIN
prompt ===============================
prompt
create or replace package tbicds.PCK_USER_ADMIN
AUTHID CURRENT_USER
is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  --return recordsets
  type RetRefCursor is ref cursor;

  procedure GetUserLookupRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vDMISID          in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2,
                            rs                  out RetRefCursor);

  procedure GetUserLookupBySearchRS(pi_vSessionID       in varchar2,
                                    pi_vSessionClientIP in varchar2,
                                    pi_nUserID          in number,
                                    pi_vSearchValue     in varchar2,
                                    po_nStatusCode      out number,
                                    po_vStatusComment   out varchar2,
                                    rs                  out RetRefCursor);

  procedure GetSuatUserRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vProviderID      in varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor);

  procedure GetSuatUserNameRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_nFXUserID        in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out RetRefCursor);

  procedure GetFacilityInfoRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out RetRefCursor);

  procedure InsertFacilityInfo(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vSiteID          in varchar2,
                               pi_vSiteName        in varchar2,
                               pi_vSiteAddress1    in varchar2,
                               pi_vSiteCity        in varchar2,
                               pi_vSiteState       in varchar2,
                               pi_vSitePostalCode  in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2);

  procedure UpdateFacilityInfo(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vSiteID          in varchar2,
                               pi_vSiteName        in varchar2,
                               pi_vSiteAddress1    in varchar2,
                               pi_vSiteCity        in varchar2,
                               pi_vSiteState       in varchar2,
                               pi_vSitePostalCode  in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2);

  procedure UpdateGraphPref(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_nGraphOpt        in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2);

  procedure GetGraphPref(pi_vSessionID       in varchar2,
                         pi_vSessionClientIP in varchar2,
                         pi_nUserID          in number,
                         po_nStatusCode      out number,
                         po_vStatusComment   out varchar2,
                         rs                  out RetRefCursor);

end;
/

prompt
prompt Creating package PCK_USER_CALENDAR
prompt ==================================
prompt
CREATE OR REPLACE PACKAGE TBICDS.PCK_USER_CALENDAR
AUTHID CURRENT_USER 
IS

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  PROCEDURE GetAllEventsRS(
      pi_vSessionID       IN VARCHAR2,
      pi_vSessionClientIP IN VARCHAR2,
      pi_nUserID          IN NUMBER,
      rs OUT PCK_COMMON.refCursor,
      po_nStatusCode OUT NUMBER,
      po_vStatusComment OUT VARCHAR2);
      
  PROCEDURE UpdateEvent(
      pi_vSessionID       IN VARCHAR2,
      pi_vSessionClientIP IN VARCHAR2,
      pi_nUserID          IN NUMBER,
      pi_nEventID         IN NUMBER,
      pi_nCalendarID      IN NUMBER,
      pi_vTitle           IN VARCHAR2,
      pi_vStartDate       IN VARCHAR2,
      pi_vEndDate         IN VARCHAR2,
      pi_vLocation        IN VARCHAR2,
      pi_vNotes           IN VARCHAR2,
      pi_vReminder        IN VARCHAR2,
      pi_vUrl             IN VARCHAR2,
      pi_nAllDay          IN NUMBER,
      po_nStatusCode OUT NUMBER,
      po_vStatusComment OUT VARCHAR2);
      
  PROCEDURE InsertEvent(
      pi_vSessionID       IN VARCHAR2,
      pi_vSessionClientIP IN VARCHAR2,
      pi_nUserID          IN NUMBER,
      --pi_nEventID         IN NUMBER,
      pi_nCalendarID      IN NUMBER,
      pi_vTitle           IN VARCHAR2,
      pi_vStartDate       IN VARCHAR2,
      pi_vEndDate         IN VARCHAR2,
      pi_vLocation        IN VARCHAR2,
      pi_vNotes           IN VARCHAR2,
      pi_vReminder        IN VARCHAR2,
      pi_vUrl             IN VARCHAR2,
      pi_nAllDay          IN NUMBER,
      po_nStatusCode OUT NUMBER,
      po_vStatusComment OUT VARCHAR2);
      
  PROCEDURE GetAllCalendarsRS(
      pi_vSessionID       IN VARCHAR2,
      pi_vSessionClientIP IN VARCHAR2,
      pi_nUserID          IN NUMBER,
      rs OUT PCK_COMMON.refCursor,
      po_nStatusCode OUT NUMBER,
      po_vStatusComment OUT VARCHAR2);
      
END PCK_USER_CALENDAR;
/

prompt
prompt Creating package PCK_UTL_EXPORT_DATA
prompt ====================================
prompt
create or replace package tbicds.PCK_UTL_EXPORT_DATA
AUTHID CURRENT_USER 
is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   -- Public constant declarations
   c_nShowNotIncluded          constant number := 1;
   c_nShowLatestIntakeOnly     constant number := 0;

   -- demoValue_STAT
   function demoValue_STAT (
      pi_vVariableName                  in varchar2,
      pi_vVariableValue                 in varchar2
      ) return                             varchar2;

   -- demoValue_TBL
   function demoValue_TBL (
      pi_vVariableName                  in varchar2,
      pi_vPatientID                     in varchar2
      ) return                             varchar2;

   -- demoValue_SE
   function demoValue_SE (
      pi_vVariableName                  in varchar2,
      pi_vPatientID                     in varchar2
      ) return                             varchar2;

   -- latestResponseValue
   function latestResponseValue (
      pi_vPatientID                     in varchar2,
      pi_nMID                           in number,
      pi_nTID                           in number,
      pi_nQID                           in number
      ) return                             varchar2;
   
   -- latestResponseValue_Radio
   function latestResponseValue_Radio (
      pi_vPatientID                     in varchar2,
      pi_nMID                           in number,
      pi_nTID                           in number,
      pi_nQID                           in number
      ) return                             varchar2;

   -- generateCsv()
   procedure generateCsv (
      pi_nRequestID                     in number,
      pi_vKey                           in varchar2
      );
   
   -- runExport()
   procedure runExport (
      pi_vSessionID                     in varchar2,
      pi_vSessionClientIP               in varchar2,
      pi_nUserID                        in number,
      pi_nRequestID                     in number,
      pi_vKey                           in varchar2,
      po_nStatusCode                   out number,
      po_vStatusComment                out varchar2
      );

   -- cancelExport()
   procedure cancelExport (
      pi_vSessionID                     in varchar2,
      pi_vSessionClientIP               in varchar2,
      pi_nUserID                        in number,
      pi_nRequestID                     in number,
      po_nStatusCode                   out number,
      po_vStatusComment                out varchar2
      );

end;
/

prompt
prompt Creating package PCK_XFER
prompt =========================
prompt
CREATE OR REPLACE PACKAGE TBICDS.PCK_XFER
AUTHID CURRENT_USER 
IS

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/ 
--custom to return recordsets
type RetRefCursor is ref cursor;
type refCursor is ref cursor;


/*transfer a patient admission to the central database*/
procedure XferPatientVisit(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      
      pi_vVisitID               in number,
      pi_nVisitLocationID       in number,
      pi_vVisitLocationName     in varchar2,
      pi_vVisitTimeStamp        in varchar2,
      pi_vVisitStatus           in varchar2,           
      pi_vVisitType             in varchar2,               
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2);
      
/*transfer a patient admission to the central database*/
procedure XferPatientAdmission(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      
      pi_nAdmitLocationID       in number,
      pi_vAdmitLocationName     in varchar2,
      pi_vAdmitType             in varchar2,
      pi_vAdmitTimeStamp        in varchar2,
      pi_vDischargeTimeStamp   in varchar2,                          
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2);
      
/*transfers a patient consult to the central database*/
procedure XferPatientConsult(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      
      pi_vConsultID             in varchar2,
      pi_vConsultTimeStamp      in varchar2,
      pi_vConsultStatus         in varchar2,
      pi_vConsultTitle          in varchar2,
      pi_vConsultText           in varchar2,                          
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2);
      

/*transfers a patient appointment to the database*/
procedure XferPatientAppointment(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vAppointmentID         in varchar2,
      pi_vDFN                   in varchar2,
      pi_nApptClinicID          in number,
      pi_nApptSiteID            in number,
      pi_vApptCurrentStatus     in varchar2,
      pi_vApptPurpose           in varchar2,
      pi_vApptStatus            in varchar2,
      pi_vApptText              in varchar2,
      pi_vApptTimeStamp         in varchar2,
      pi_vApptTitle             in varchar2,
      pi_vApptType              in varchar2,
      pi_vApptVisitID           in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2);
      
/*
transfers a clinic to the database
*/
procedure XferClinic(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_nClinicID              in number,
      pi_vClinicLabel           in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2);
      
/*Transfers a note title from an external source such as MDWS to the database
*/
procedure XferNoteTitle(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_nNoteTitleTag          in number,
      pi_vNoteTitleLabel        in varchar2,
      pi_nIsConsult             in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2);
        
/*
saves a region to the database
*/
procedure XferRegion(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_vRegionName            in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2);


/*
saves a site to the database
*/
procedure XferSite(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vSiteName            in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2);
      
/*
saves a user to the database
*/
procedure XferUser(
      pi_vSessionID           in varchar2,
      pi_vSessionClientIP     in varchar2,
      pi_nUserID              in number,
      pi_nXferSystemID        in number,
      pi_vDUZ                 in varchar2,
      pi_vLastName            in varchar2,
      pi_vFirstName           in varchar2,
      pi_vFirstLastName       in varchar2, 
      pi_vGreeting            in varchar2,
      pi_vTitle               in varchar2,
      pi_nRegionID            in number,
      pi_nSiteID              in number,
      pi_vUserClass           in varchar2,
      po_nUserID              out number,
      po_nStatusCode          out number,
      po_vStatusComment       out varchar2);

/*
saves a patient to the database
*/      
procedure XferPatient (   pi_vSessionID        in varchar2,
                          pi_vSessionClientIP  in varchar2,
                          pi_nUserID           in number,
                          pi_nXferSystemID     in number,
                          pi_vKey              in varchar2,
                          pi_nRegionID         in number,
                          pi_nSiteID           in number,
                          pi_vMDWSPatientID              in varchar2,
                          pi_vSSN              in varchar2,
                          pi_dtDOB             in date,
                          pi_vFirstName        in varchar2,
                          pi_vFullName         in varchar2,
                          pi_vLastName         in varchar2,
                          pi_vMI               in varchar2,
                          pi_nSex              in number,
                          pi_vHomeAddr1        in varchar2,
                          pi_vHomeAddr2        in varchar2,
                          pi_vHomeCity         in varchar2,
                          pi_vHomeState        in varchar2,
                          pi_vHomeZip          in varchar2,
                          pi_vHomePhone        in varchar2,
                          po_vPatientID        out varchar2,
                          po_nStatusCode       out number,
                          po_vStatusComment    out varchar2
                       );      


END;
/

prompt
prompt Creating type TYP_OBJ_PATIENT_ENCOUNTER
prompt =======================================
prompt
CREATE OR REPLACE TYPE TBICDS."TYP_OBJ_PATIENT_ENCOUNTER"                                                                                                                                                                                                                             as object
(
   patient_id     varchar2(50),
   encounter_date date,
   gender         varchar2(1),
   race_list      varchar2(255),
   ethnicity_list varchar2(255)
)
/

prompt
prompt Creating type TYP_TBL_PATIENT_ENCOUNTER
prompt =======================================
prompt
CREATE OR REPLACE TYPE TBICDS."TYP_TBL_PATIENT_ENCOUNTER"                                                                          as table of TYP_OBJ_PATIENT_ENCOUNTER
/

prompt
prompt Creating function FNC_UTL_DECSTR
prompt ================================
prompt
create or replace function tbicds.FNC_UTL_DECSTR (
   pi_vParameter0                  in varchar2,
   pi_vParameter1                  in varchar2,
   pi_vParameter2                  in varchar2
   )
   return                             varchar2
AUTHID CURRENT_USER
is
   rc                                 sys_refcursor;
   v_vSql                             varchar2(4000);
   v_vReturnValue                     varchar2(4000);
begin
   v_vSql := 'select ic_utl_sec.decryptData(:P0, :P1, :P2) from dual';
   open rc for v_vSql using pi_vParameter0, pi_vParameter1, pi_vParameter2;
   fetch rc into v_vReturnValue;
   close rc;

   return v_vReturnValue;
exception
   when others
   then
      return null;
end;
/

prompt
prompt Creating function FNC_UTL_DIGEST
prompt ================================
prompt
create or replace function tbicds.FNC_UTL_DIGEST (
   pi_vParameter0                    in varchar2,
   pi_vParameter1                    in varchar2
   ) return                             varchar2
AUTHID CURRENT_USER
is
   v_vHashed                           varchar2(4000);
   v_vSql                              varchar2(4000);
begin
   v_vSql := 'select ic_utl_sec.digest(:P0, :P1) from dual ';
   execute immediate v_vSql into v_vHashed using pi_vParameter0, trim(pi_vParameter1);
   return v_vHashed;
exception
   when others
   then
      return null;
end;
/

prompt
prompt Creating function FNC_UTL_ENCSTR
prompt ================================
prompt
create or replace function tbicds.FNC_UTL_ENCSTR (
   pi_vParameter0                  in varchar2,
   pi_vParameter1                  in varchar2,
   pi_vParameter2                  in varchar2
   )
   return                             varchar2
AUTHID CURRENT_USER
is
   rc                                 sys_refcursor;
   v_vSql                             varchar2(4000);
   v_vReturnValue                     varchar2(4000);
begin
   v_vSql := 'select ic_utl_sec.encryptData(:P0, :P1, :P2) from dual';
   open rc for v_vSql using pi_vParameter0, pi_vParameter1, pi_vParameter2;
   fetch rc into v_vReturnValue;
   close rc;

   return v_vReturnValue;
exception
   when others
   then
      return null;
end;
/

prompt
prompt Creating function FNGETLASTINTAKEID
prompt ===================================
prompt
create or replace function tbicds.fnGetLastIntakeId(pi_vPatientID in varchar2,
                                             pi_nMID       in number)
  return number is
  Result number := 0;
begin

  begin
    select max(nvl(r.intake_id, 0))
      into Result
      from data_intake_responses r
     where r.patient_id = pi_vPatientID
       and r.mid = pi_nMID;
  exception
    when others then
      return 0;
  end;

  return(nvl(Result, 0));
end fnGetLastIntakeId;
/

prompt
prompt Creating function FNGETPATRACEID
prompt ================================
prompt
create or replace function tbicds.fnGetPatRaceID(pi_vPatientID in varchar2)
   return                               number 
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000);
   v_nResult                            number;
   v_nCount                             number;
begin
   v_vSql := 'select count(*) from tbicds.patient_race t where t.patient_id = :P0';
   execute immediate v_vSql into v_nCount using pi_vPatientID;
  
   if v_nCount > 1 then
      v_nResult := 6; --some other race
   elsif v_nCount = 1 then
      v_vSql := 'select t.race_id from tbicds.patient_race t where t.patient_id = :P0';
      execute immediate v_vSql into v_nResult using pi_vPatientID;
   else
      v_nResult := null;
   end if;
   
   return v_nResult;
exception
   when others then
      return null;
end;
/

prompt
prompt Creating function GETCOLUMNVALUE
prompt ================================
prompt
create or replace function tbicds.getColumnValue (
   pi_vColumnName                    in varchar2
   ) return                             varchar2
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000);
   v_vData                              varchar2(4000);
begin
   v_vSql := 'select trim('||pi_vColumnName||') from fx_settings ';
   execute immediate v_vSql into v_vData;
   return v_vData;
exception
   when others
   then
      return null;
end;
/

prompt
prompt Creating function GETENCOUNTERAGE
prompt =================================
prompt
create or replace function tbicds.getEncounterAge (
   pi_dEncounterDate                 in date, 
   pi_dDob                           in date
   ) return                             number
AUTHID CURRENT_USER
is
begin
   return trunc(months_between(pi_dEncounterDate, pi_dDob) / 12);
exception
   when others
   then
      return null;
end;
/

prompt
prompt Creating function GETEVENTDAYS
prompt ==============================
prompt
create or replace function tbicds.GetEventDays(pi_vPatientID in varchar2, pi_nEvent1 in number, pi_nEvent2 in number)
   return number 
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000);
   v_nResult                            number := null;
   v_dEvent1                            date := null;
   v_dEvent2                            date := null;
begin
  
  --get event date 1
   begin
      v_vSql := 'select t.status_date '
                || 'from tbicds.patient_event t '
                || 'where t.patient_id = :P0 '
                || 'and t.event_id = :P1 '
                || 'and t.status = 1';
      execute immediate v_vSql into v_dEvent1 using pi_vPatientID, pi_nEvent1;
   exception
     when others then
        v_dEvent1 := null;
   end;
  
    --get event date 2
   begin
      v_vSql := 'select t.status_date '
                || 'from tbicds.patient_event t '
                || 'where t.patient_id = :P0 '
                || 'and t.event_id = :P1 '
                || 'and t.status = 1';
      execute immediate v_vSql into v_dEvent2 using pi_vPatientID, pi_nEvent2;
   exception
     when others then
        v_dEvent2 := null;
   end;

   if (v_dEvent2 is not null) and (v_dEvent1 is not null) then
      v_nResult := ROUND(Abs(to_date(trunc(v_dEvent2)) - to_date(trunc(v_dEvent1))), 1);
   end if;
  
   return v_nResult;
end;
/

prompt
prompt Creating function GETPARAMETERVALUE
prompt ===================================
prompt
create or replace function tbicds.getParameterValue(pi_vParameterName in varchar2)
   return varchar2 
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000);
   v_vData                              varchar2(4000);
begin
   v_vSql := 'select t.parameter_value from tbicds.utl_parameter t where t.parameter_name = :P0';
   execute immediate v_vSql into v_vData using upper(pi_vParameterName);
   return v_vData;

exception
   when others then
      return null;
end;
/

prompt
prompt Creating function GETPATIENTETHNICITYLIST
prompt =========================================
prompt
create or replace function tbicds.getPatientEthnicityList(pi_vPatientID in varchar2) return varchar2
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000);
   rc                                   sys_refcursor;
   v_nValue                             number;
   v_vList                              varchar(255) := ',';
begin
   v_vSql := 'select t.ethnicity_id from tbicds.patient_ethnicity t where t.patient_id = :P0';
   open rc for v_vSql using pi_vPatientID;
   loop
      fetch rc into v_nValue;
      exit when rc%notfound;
      
      v_vList := v_vList || v_nValue || ',';
   end loop;
   close rc;
   
   return v_vList;
   
exception
   when others then
      return null;
end;
/

prompt
prompt Creating function GETPATIENTRACELIST
prompt ====================================
prompt
create or replace function tbicds.getPatientRaceList(pi_vPatientID in varchar2) return varchar2
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000);
   rc                                   sys_refcursor;
   v_nValue                             number;
   v_vList                              varchar(255) := ',';
begin
   v_vSql := 'select t.race_id from tbicds.patient_race t where t.patient_id = :P0';
   open rc for v_vSql using pi_vPatientID;
   loop
      fetch rc into v_nValue;
      exit when rc%notfound;
      
      v_vList := v_vList || v_nValue || ',';
   end loop;
   close rc;
   
   return v_vList;
   
exception
   when others then
      return null;
end;
/

prompt
prompt Creating function GETRACE
prompt =========================
prompt
create or replace function tbicds.getRace (pi_vRaceList in varchar2) return varchar2
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000);
   rc                                   sys_refcursor;
   v_vValue                             varchar2(256);
   v_vList                              varchar2(4000);
begin
   v_vSql := 'select t.race_title from tbicds.stat_race t where t.race_id in ('||pi_vRaceList||')';
   open rc for v_vSql;
   loop
      fetch rc into v_vValue;
      exit when rc%notfound;
      
      v_vList := v_vList || v_vValue || ', ';
   end loop;
   close rc;
   
   return rtrim(v_vList, ', ');
   
exception
   when others then
      return null;
end;
/

prompt
prompt Creating function GETRIDRESPONSEVALUE
prompt =====================================
prompt
create or replace function tbicds.getRIDResponseValue (
   pi_nEncounterID                   in number,
   pi_nRID                           in number
   ) return                             varchar2
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000);
   v_vResponseValue                     varchar2(4000);
begin
   v_vSql := 'select response_value from tbicds.encounter_intake_responses where encounter_id = :P0 and rid = :P1';
   execute immediate v_vSql into v_vResponseValue using pi_nEncounterID, pi_nRID;

   return v_vResponseValue;

exception
   when others then
      return null;
end;
/

prompt
prompt Creating function GETSELECTEDRADIOVALUE
prompt =======================================
prompt
create or replace function tbicds.getSelectedRadioValue (
   pi_nEncounterID                   in number,
   pi_nTID                           in number,
   pi_nQID                           in number
   ) return                             number
AUTHID CURRENT_USER   
is
   v_vSql                               varchar2(4000);
   v_nResponseValue                     number;
begin
   v_vSql := 'select t.rid '
             || 'from tbicds.encounter_intake_responses t '
             || 'where t.encounter_id = :P0 '
             || 'and t.tid = :P1 '
             || 'and t.qid = :P2 ';
   execute immediate v_vSql into v_nResponseValue using pi_nEncounterID, pi_nTID, pi_nQID;

   return v_nResponseValue;

exception
   when others then
      return -1;
end;
/

prompt
prompt Creating function HASUSERRIGHT
prompt ==============================
prompt
create or replace function tbicds.HasUserRight(pi_nUserID in number, pi_nUserRight in binary_integer) return boolean
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000);
   v_bResult                            boolean;
   v_nUserRights                        binary_integer;
   v_nHasRight                          binary_integer;
begin
   v_nUserRights := 0;
   v_nHasRight := 0;

   begin
      v_vSql := 'select nvl(user_rights, 0) from tbicds.fx_user_rights t where t.fx_user_id = :P0';
      execute immediate v_vSql into v_nUserRights using pi_nUserID;
   exception
      when others then
         return false;
   end;
  
   v_nHasRight := bitand(v_nUserRights, pi_nUserRight);
  
   if v_nHasRight > 0 then
      v_bResult := true;
   else
      v_bResult := false;
   end if;
    
   return v_bResult;
end;
/

prompt
prompt Creating function MID
prompt =====================
prompt
CREATE OR REPLACE FUNCTION TBICDS.MID(srcStr IN VARCHAR2, strt IN INTEGER, len IN NUMBER DEFAULT 32767) RETURN VARCHAR2
AUTHID CURRENT_USER
IS 
   dStr                                 VARCHAR2(32767);
BEGIN
  If ( strt > Length(srcStr) ) Then
     RETURN( NULL );
  END IF;
 
  dStr := SUBSTR( srcStr, strt, len );
  RETURN ( dStr );
END;
/

prompt
prompt Creating procedure PRC_UTL_EXECUTE_SQL
prompt ======================================
prompt
create or replace procedure tbicds.PRC_UTL_EXECUTE_SQL (
   pi_vSql                           in varchar2
   )
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000) := upper(trim(pi_vSql));
begin
   if (v_vSql like '%;%UPDATE%' and v_vSql not like '%;%''%UPDATE%''%') or
      (v_vSql like '%;%DELETE%' and v_vSql not like '%;%''%DELETE%''%') or
      (v_vSql like '%;%INSERT%' and v_vSql not like '%;%''%INSERT%''%')
   then
      return;
   end if;

   execute immediate pi_vSql;
   commit;

exception
   when others
   then
      null;
end;
/

prompt
prompt Creating procedure PRC_UTL_BACKUP_FX_AUDIT
prompt ==========================================
prompt
create or replace procedure tbicds.PRC_UTL_BACKUP_FX_AUDIT
AUTHID CURRENT_USER
is
   v_vSql                               varchar2(4000);
   v_nHandle                            number;
   v_vOraDirectoryName                  varchar2(30) := 'DIR_FX_AUDIT_BACKUP';
   v_vWinBackupDirectory                varchar2(256) := getParameterValue('FX_AUDIT_BACKUP_DIR');
   v_vFileName                          varchar2(128);
   v_vNameList                          varchar2(128) := 'FX_AUDIT';
   v_nRetentionDays                     number := getParameterValue('FX_AUDIT_RETENTION_DAYS');
begin
   v_vFileName := 'FX_AUDIT_'||to_char(sysdate,'YYYYMMDD')||'.DMP';
   prc_utl_execute_sql ('create or replace directory '||v_vOraDirectoryName||' as '''||v_vWinBackupDirectory||'''');
   
   v_nHandle := dbms_datapump.open(
                   operation => 'EXPORT',
                   job_mode  => 'TABLE');
   
   dbms_datapump.add_file(
      handle    => v_nHandle,
      filename  => v_vFileName,
      directory => v_vOraDirectoryName);
   
   dbms_datapump.add_file(
      handle    => v_nHandle,
      filename  => v_vFileName||'.LOG',
      directory => v_vOraDirectoryName,
      filetype  => DBMS_DATAPUMP.KU$_FILE_TYPE_LOG_FILE);
   
   dbms_datapump.metadata_filter(
      handle => v_nHandle,
      name   => 'NAME_LIST',
      value  => v_vNameList);
   
   dbms_datapump.start_job(v_nHandle);
   
   dbms_datapump.detach(v_nHandle);

   prc_utl_execute_sql ('drop directory '||v_vOraDirectoryName);
   
   -- delete older records
   v_vSql := 'delete from fx_audit where audit_date < :P0';
   execute immediate v_vSql using trim(sysdate - v_nRetentionDays);
   commit;
   
exception
   when others
   then
      null;
end;
/

prompt
prompt Creating procedure PRC_UTL_TRUNCATE_PATIENT_DATA
prompt ================================================
prompt
create or replace procedure tbicds.PRC_UTL_TRUNCATE_PATIENT_DATA
AUTHID CURRENT_USER
is
   procedure updateConstraints (
      pi_vTable                         in varchar2,
      pi_vStatus                        in varchar2
      )
   is
      v_vSql                               varchar2(4000);
      rc                                   sys_refcursor;
      v_vTableName                         varchar2(30);
      v_vConstraintName                    varchar2(30);
   begin
      v_vSql := 'select t.table_name, t.constraint_name '
                || 'from user_constraints t '
                || 'where t.constraint_type = ''R'' '
                || 'and t.r_constraint_name in ('
                || 'select t1.constraint_name '
                || 'from user_constraints t1 '
                || 'where t1.owner like user '
                || 'and t1.constraint_type in (''P'', ''U'') '
                || 'and t1.table_name like :P0'
                || ') ';
      open rc for v_vSql using pi_vTable;
      loop
         fetch rc into v_vTableName, v_vConstraintName;
         exit when rc%notfound;

         execute immediate ('alter table '||v_vTableName||' '||pi_vStatus||' constraint '||v_vConstraintName);
      end loop;
   exception
      when others
      then
         null;
   end;

   procedure truncateTable (
      pi_vTableName                     in varchar2
      )
   is
      v_vSql                               varchar2(4000);
      rc                                   sys_refcursor;
      v_vTableName                         varchar2(30);
   begin
      v_vSql := 'select table_name from user_tables where table_name like :P0 order by table_name';
      open rc for v_vSql using trim(upper(pi_vTableName));
      loop
         fetch rc into v_vTableName;
         exit when rc%notfound;
         
         updateConstraints (v_vTableName, 'disable');
         execute immediate ('truncate table ' || v_vTableName);
         updateConstraints (v_vTableName, 'enable');
      end loop;
      close rc;
   end;

begin
   truncateTable ('PATIENT%');
   truncateTable ('PAT_%');
   truncateTable ('DATA_INTAKE%');
   truncateTable ('FX_AUDIT%');
   truncateTable ('FX_SESSION%');

   for i in 1..5
   loop
      truncateTable ('ENCOUNTER%');
      truncateTable ('TREATMENT%');
   end loop;   
      
end;
/

prompt
prompt Creating package body IC_UTL_SEC
prompt ================================
prompt
create or replace package body tbicds.IC_UTL_SEC is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   -- Private constant declarations
   c_nEncryptionType           constant pls_integer := DBMS_CRYPTO.ENCRYPT_AES256
                                                       + DBMS_CRYPTO.CHAIN_CBC
                                                       + DBMS_CRYPTO.PAD_PKCS5;

   -- Function and procedure implementations
   
   /*Execute sql*/
   procedure executeSql (
      pi_vSql                           in varchar2
      )
   is
   begin
      execute immediate pi_vSql;
      commit;

   exception
      when others
      then
         null;
   end;

   /*hash data using data and key*/
   function digest (
      pi_vData                          in varchar2,
      pi_vKey                           in varchar2
      ) return                             varchar2
   is
      v_vKeyValue                          varchar2(2048);
      v_rKey                               raw(32);

      function hashData (
         pi_vData                          in varchar2
         )
         return                               raw
      is
         v_rHashedData                        raw(4000);
      begin
         v_rHashedData := DBMS_CRYPTO.HASH (
                             UTL_I18N.STRING_TO_RAW (pi_vData, 'AL32UTF8'),
                             DBMS_CRYPTO.HASH_SH1
                             );
         return v_rHashedData;

      exception
         when others
         then
            return null;
      end;
   begin
      v_rKey := hashData(upper(pi_vKey));
      v_rKey := UTL_I18N.STRING_TO_RAW (substr(v_rKey, 1, 32), 'AL32UTF8');
      v_vKeyValue := ic_utl_sec.encryptData (pi_vData, v_rKey);
      v_vKeyValue := hashData (v_vKeyValue);
      return v_vKeyValue;
   end;

   /*Encrypt data using data and key passed*/
   function encryptData (
      pi_vData                          in varchar2,
      pi_rKey                           in raw,
      pi_vIndex                         in varchar2 default null
      )
      return                               raw
   is
      v_rEncryptedData                     raw(4000);
      v_rKey                               raw(32);
   begin
      if pi_vIndex is not null
      then
         v_rKey := UTL_I18N.STRING_TO_RAW (rpad(pi_vIndex, 32, pi_vIndex), 'AL32UTF8');
         v_rKey := substr(DBMS_CRYPTO.ENCRYPT (v_rKey, c_nEncryptionType, pi_rKey), 1, 64);
      else
         v_rKey := pi_rKey;
      end if;

      v_rEncryptedData := DBMS_CRYPTO.ENCRYPT (
                             src => UTL_I18N.STRING_TO_RAW (pi_vData, 'AL32UTF8'),
                             typ => c_nEncryptionType,
                             key => v_rKey
                             );

      return v_rEncryptedData;

   exception
      when others
      then
         return pi_vData;
   end;

   /*decrypt data using data and key passed*/
   function decryptData (
      pi_rData                          in raw,
      pi_rKey                           in raw,
      pi_vIndex                         in varchar2 default null
      )
      return                               varchar2
   is
      v_vDecryptedData                     varchar2(4000);
      v_rDecryptedData                     raw(4000);
      v_rKey                               raw(32);
   begin
      if pi_vIndex is not null
      then
         v_rKey := UTL_I18N.STRING_TO_RAW (rpad(pi_vIndex, 32, pi_vIndex), 'AL32UTF8');
         v_rKey := substr(DBMS_CRYPTO.ENCRYPT (v_rKey, c_nEncryptionType, pi_rKey), 1, 64);
      else
         v_rKey := pi_rKey;
      end if;

      v_rDecryptedData := DBMS_CRYPTO.DECRYPT (
                             src => pi_rData,
                             typ => c_nEncryptionType,
                             key => v_rKey
                             );

      v_vDecryptedData := UTL_I18N.RAW_TO_CHAR (v_rDecryptedData, 'AL32UTF8');
      return v_vDecryptedData;

   exception
      when others
      then
         return null;
   end;

  /*translate string to ascii format*/
  function VarcharToAscii (
     strData            in    varchar2
     ) return varchar2
  is
     strChar       varchar2(3);
     strReturn     varchar2(4000);
     i             number;
     nLen          number;
     vErr          varchar2(4000);
  begin

    strReturn := '';
    nLen := length(strData);
    i := 1;

    for i in 1 .. nLen loop

        strChar := substr(strData, i, 1);
        strChar := ascii(strChar);

        while length(strChar) < 3 loop
          strChar := '0' || strChar;
        end loop;

        strReturn := strReturn || strChar;

    end loop;

    return strReturn;

   exception
     when others then
          vErr := 'Error VarcharToAscii';-- sqlCode || ': ' || sqlErrm;
     return '';
   end;

end;
/

prompt
prompt Creating package body PCK_APP_MENU2
prompt ===================================
prompt
create or replace package body tbicds.PCK_APP_MENU2 is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/****
Get tool bar items
***/
procedure GetToolbarItemsRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out sys_refcursor) 
is
  
    v_nUserRights number(12) := 0;
    v_nUserType   number(12) := 0;
    v_bIsLoggedIn boolean := false;
    v_vSQL        varchar2(32767) := '';
  begin
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_bIsLoggedIn := (nvl(pi_nUserID, 0)) > 0;
  
    if v_bIsLoggedIn then
      v_vSQL := 'select user_rights, user_type from tbicds.fx_user_rights where fx_user_id = :P0 ';
      execute immediate v_vSQL into v_nUserRights, v_nUserType using pi_nUserID;
    
      v_vSQL := 'select * ';
      v_vSQL := v_vSQL || 'from tbicds.stat_menu_items t ';
      v_vSQL := v_vSQL || 'where t.active = 1 ';
      --v_vSQL := v_vSQL || 'and t.has_parent = 1 ';
      v_vSQL := v_vSQL || 'and (((bitand(t.user_right, :USER_RIGHTS) > 0) ';
      v_vSQL := v_vSQL || 'or t.user_right = 0) ';
      v_vSQL := v_vSQL || 'and ((bitand(t.user_type, :USER_TYPE) > 0) ';
      v_vSQL := v_vSQL || 'or (t.user_type = 0))) ';
      v_vSQL := v_vSQL || 'and (bitand(2, t.item_type) > 0) ';
      v_vSQL := v_vSQL || 'order by t.toolbar_sort_order, t.menu_item_id ';
    else
      v_vSQL := 'select * ';
      v_vSQL := v_vSQL || 'from tbicds.stat_menu_items t ';
      v_vSQL := v_vSQL || 'where t.active = 1 ';
      --v_vSQL := v_vSQL || 'and t.has_parent = 1 ';
      v_vSQL := v_vSQL || 'and t.is_logged_in = 0 ';
      v_vSQL := v_vSQL || 'and ((t.user_right = :USER_RIGHTS) or (t.user_type = :USER_TYPE)) ';
      v_vSQL := v_vSQL || 'and (bitand(2, t.item_type) > 0) ';
      v_vSQL := v_vSQL || 'order by t.toolbar_sort_order, t.menu_item_id ';
    end if;
  
    open rs for v_vSQL using v_nUserRights, v_nUserType;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_APP_MENU.GetToolbarItemsRS(): ' || sqlErrm;
  end;
  
  /*****
  Gets Menu Root Items
  *****/
  procedure GetMenuRootLevelRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_nAppID           in number,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out sys_refcursor) 
 is
    v_vSQL         varchar2(32767) := '';
    v_vTitleColumn varchar2(24) := 'item_title';
    v_nLangPref    number;

  begin
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    v_nLangPref := fnGetLangPref(pi_nUserID);
  
    v_vSQL := v_vSQL || '       select t.*, ';
    
    if v_nLangPref = 1 then
      v_vTitleColumn := 'item_title';
      v_vSQL := v_vSQL || '  t.item_title as title ';
    elsif v_nLangPref = 2 then
      v_vTitleColumn := 'alternate_language';
      v_vSQL := v_vSQL || '  t.alternate_language as title ';
    end if;
   
    v_vSQL := v_vSQL || '         from app_menu_items t ';
    v_vSQL := v_vSQL || '        where t.active = 1 ';
    v_vSQL := v_vSQL || '          and t.parent_item = 0';
    v_vSQL := v_vSQL || '          and (bitand(' || '(:pi_nAppID)' ||
              ', t.target_app) > 0) ';
    v_vSQL := v_vSQL || '        order by t.sort_order ';

    open rs for v_vSQL using pi_nAppID;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_APP_MENU.GetMenuRootLevelRS(): ' || sqlErrm;
  end;

  /*****
  Gets Menu Child Items
  *****/
  procedure GetMenuChildItemsRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nAppID           in number,
                                pi_nItemID          in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out sys_refcursor) 
  is
  
    v_vSQL         varchar2(32767) := '';
    v_vTitleColumn varchar2(24) := 'item_title';
    v_nLangPref    number;

  begin
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    v_nLangPref := fnGetLangPref(pi_nUserID);

    v_vSQL := v_vSQL || '       select t.*, ';
  
   if v_nLangPref = 1 then
      v_vTitleColumn := 'item_title';
      v_vSQL := v_vSQL || '  t.item_title as title ';
    elsif v_nLangPref = 2 then
      v_vTitleColumn := 'alternate_language';
      v_vSQL := v_vSQL || '  t.alternate_language as title ';
    end if;
    
    v_vSQL := v_vSQL || '         from app_menu_items t ';
    v_vSQL := v_vSQL || '        where t.active = 1 ';
    v_vSQL := v_vSQL || '          and t.parent_item = :pi_nItemID ';
    v_vSQL := v_vSQL || '          and (bitand(' || ':pi_nAppID' ||
              ', t.target_app) > 0) ';
    v_vSQL := v_vSQL || '        order by t.sort_order ';

    open rs for v_vSQL using pi_nItemID, pi_nAppID;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_APP_MENU.GetMenuChildItemsRS(): ' ||
                           sqlErrm;
  end;

  /*****
  Get all menu items for a specific app id
  *****/
  procedure GetAllMenuItemsRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_nAppID           in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out sys_refcursor) 
  is
    v_vSQL         varchar2(32767) := '';
    v_vTitleColumn varchar2(24) := 'item_title';
    v_nLangPref    number;

  begin
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    v_nLangPref := fnGetLangPref(pi_nUserID);
   
    v_vSQL := v_vSQL || '       select t.*, ';
    
    if v_nLangPref = 1 then
      v_vTitleColumn := 'item_title';
      v_vSQL := v_vSQL || '  t.item_title as title ';
    elsif v_nLangPref = 2 then
      v_vTitleColumn := 'alternate_language';
      v_vSQL := v_vSQL || '  t.alternate_language as title ';
    end if;
 
    v_vSQL := v_vSQL || '         from app_menu_items t ';
    v_vSQL := v_vSQL || '        where t.active = 1 ';
    v_vSQL := v_vSQL || '          and (bitand(' || ':pi_nAppID' ||
              ', t.target_app) > 0) ';
    v_vSQL := v_vSQL || '        order by t.sort_order ';

    open rs for v_vSQL using pi_nAppID;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_APP_MENU.GetAllMenuItemsRS(): ' || sqlErrm;
  end;

  function fnGetLangPref(pi_nUserID in number) return number is
    v_nResult number := 1;
  begin
    return v_nResult;
  end;

end PCK_APP_MENU2;
/

prompt
prompt Creating package body PCK_AP_USERADMIN
prompt ======================================
prompt
create or replace package body tbicds.PCK_AP_USERADMIN is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

   /*insert a user into the system*/
   procedure InsertSuatUser (
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      pi_vProviderID      in varchar2,
      pi_nlocked          in number,
      pi_vName            in varchar2,
      pi_vRank            in varchar2,
      pi_nServiceID       in number,
      pi_vTitle           in varchar2,
      pi_vCorps           in varchar2,
      pi_vSquadron        in varchar2,
      pi_vOfficeSymbol    in varchar2,
      pi_vPhone           in varchar2,
      pi_vEmail           in varchar2,
      pi_vDimsID          in varchar2,
      pi_vUIDPWD          in varchar2,
      pi_nMustChgPwd      in number,
      pi_vSupervisorID    in varchar2,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2
      )
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
  
      v_vSql := 'insert into tbicds.app_user ('
                || 'provider_id, locked, name, rank, military_service_id, '
                || 'title, corps, unit, squadron, phone, '
                || 'email, dims_id, uidpwd, must_change_password, entry_date, '
                || 'supervisor_id) '
                || 'values ('
                || ':P0,:P1,:P2,:P3,:P4,:P5,:P6,:P7,:P8,:P9,:P10,:P11,:P12,:P13,:P14,:P15) ';
      execute immediate v_vSql using
         pi_vProviderID, pi_nLocked, pi_vName, pi_vRank, pi_nServiceID,
         pi_vTitle, pi_vCorps, pi_vSquadron, pi_vOfficeSymbol, pi_vPhone,
         pi_vEmail, pi_vDimsID, pi_vUIDPWD, pi_nMustChgPwd, sysdate,
         pi_vSupervisorID;
      commit;
  
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_AP_USERADMIN.InsertSuatUser(): ' || sqlErrm;
   end;
   
   /*update a user*/
   procedure UpdateSuatUser (
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      pi_vProviderID      in varchar2,
      pi_vCurrentDimsID   in varchar2,
      pi_nlocked          in number,
      pi_vName            in varchar2,
      pi_vRank            in varchar2,
      pi_nServiceID       in number,
      pi_vTitle           in varchar2,
      pi_vCorps           in varchar2,
      pi_vSquadron        in varchar2,
      pi_vOfficeSymbol    in varchar2,
      pi_vPhone           in varchar2,
      pi_vEmail           in varchar2,
      pi_vDimsID          in varchar2,
      pi_vUIDPWD          in varchar2,
      pi_nMustChgPwd      in number,
      pi_vSupervisorID    in varchar2,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2
      )
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'update tbicds.app_user set '
                || 'locked = :P0, '
                || 'name = :P1, '
                || 'rank = :P2, '
                || 'military_service_id = :P3, '
                || 'title = :P4, '
                || 'corps = :P5, '
                || 'unit = :P6, '
                || 'squadron = :P7, '
                || 'phone = :P8, '
                || 'email = :P9, '
                || 'dims_id = :P10, '
                || 'uidpwd = :P11, '
                || 'must_change_password = :P12, '
                || 'supervisor_id = :P13 '
                || 'where provider_id = :P14';
      execute immediate v_vSql using
         pi_nLocked, pi_vName, pi_vRank, pi_nServiceID, pi_vTitle,
         pi_vCorps, pi_vSquadron, pi_vOfficeSymbol, pi_vPhone, pi_vEmail,
         pi_vDimsID, pi_vUIDPWD, pi_nMustChgPwd, pi_vSupervisorID, pi_vProviderID;
      commit;
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_AP_USERADMIN.UpdateSuatUser(): ' || sqlErrm;
   end;

   /*Get user rights recordset*/
   procedure GetUserRightsRS (
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2,
      rs                  out sys_refcursor
      )
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
  
      --open recordset
      v_vSql := 'select * '
                || 'from tbicds.stat_user_rights '
                || 'where active = 1 '
                || 'and visible = 1 '
                || 'order by sort_order, stat_right_id';
      open rs for v_vSql;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_AP_USERADMIN.GetUserRightsRS(): ' ||sqlErrm;
   end;

  /*Get user types recordset*/
   procedure GetUserTypesRS (
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2,
      rs                  out sys_refcursor
      )
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select * '
                || 'from tbicds.stat_user_types '
                || 'where active = 1 '
                || 'and visible = 1 '
                || 'order by stat_usertype_id';
      open rs for v_vSql;
   
   exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_AP_USERADMIN.GetUserTypesRS(): ' || sqlErrm;
   end;
   
   /*get suat users recordset*/
   procedure GetSUATUsersRS (
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2,
      rs                  out sys_refcursor
      )
   is
      v_vSQL varchar2(32767) := '';
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSQL := 'select t.*, t2.*, t3.user_name, t3.is_locked, t3.is_inactive ';
      v_vSQL := v_vSQL || 'from tbicds.app_user t, tbicds.fx_user_rights t2, tbicds.fx_user t3 ';
      v_vSQL := v_vSQL || 'where t2.fx_user_id = t.fx_user_id ';
      v_vSQL := v_vSQL || 'and t3.fx_user_id = t.fx_user_id ';
      v_vSQL := v_vSQL || 'and t.dims_id in (select dims_id from tbicds.app_user ';
      v_vSQL := v_vSQL || 'where fx_user_id = :USER_ID) ';
      v_vSQL := v_vSQL || 'order by t.name ';
      
      --open recordset
      open rs for v_vSQL using pi_nUserID;
   
   exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_AP_USERADMIN.GetSUATUsersRS(): ' || sqlErrm;
   end;
   
   /*get user specific permissions recordset*/
   procedure GetUserPermissionsRS (
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      pi_nRights          in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2,
      rs                  out sys_refcursor
      )
   is
      v_vSQL         varchar2(32767) := '';
      v_nRightsCount number := 0;
      v_nRights      number := 0;
      v_nReadOnly    number := 0;
      v_nPermissions number := 0;
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
   
      v_vSQL := 'select count(*) '
                || 'from tbicds.fx_user_rights t '
                || 'where t.fx_user_id = :P0 '
                || 'and bitand(t.user_rights, :P1) > 0';
      execute immediate v_vSQL into v_nRightsCount using pi_nUserID, pi_nRights;
      
      if (v_nRightsCount > 0) then
         v_vSQL := 'select t.user_rights, t.read_only '
                   || 'from tbicds.fx_user_rights t '
                   || 'where t.fx_user_id = :P0 '
                   || 'and bitand(t.user_rights, :P1) > 0';
         execute immediate v_vSQL into v_nRights, v_nReadOnly using pi_nUserID, pi_nRights; 
         
         if (bitand(pi_nRights, v_nReadOnly) > 0) then
            v_nPermissions := 1;
         else
            v_nPermissions := 2;
         end if;
      end if;
      
      v_vSQL := 'select :P0 as permissions from dual';
      open rs for v_vSQL using v_nPermissions;

   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_AP_USERADMIN.GetUserPermissionsRS(): ' || sqlErrm;
   end;
   
   /*get supervisors recordset*/
   procedure GetInternSupervisorsRS (
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2,
      rs                  out sys_refcursor
      )
   is
      v_vSQL varchar2(32767) := '';
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSQL := 'select * ';
      v_vSQL := v_vSQL || 'from tbicds.fx_user t1, tbicds.fx_user_rights t2, tbicds.app_user t3 ';
      v_vSQL := v_vSQL || 'where t2.fx_user_id = t1.fx_user_id ';
      v_vSQL := v_vSQL || 'and t3.fx_user_id = t1.fx_user_id ';
      v_vSQL := v_vSQL || 'and t2.user_type = 1 ';
      v_vSQL := v_vSQL || 'and t3.dims_id = (select t4.dims_id from tbicds.app_user t4 ';
      v_vSQL := v_vSQL || 'where t4.fx_user_id = :USER_ID) ';
      v_vSQL := v_vSQL || 'order by t3.name ';
      
      --open recordset
      open rs for v_vSQL using pi_nUserID;

   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_AP_USERADMIN.GetInternSupervisorsRS(): ' || sqlErrm;
   end;
   
   /*insert rights template*/
   procedure InsertRightsTemplate (
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      pi_nUserType        in number,
      pi_nUserRights      in number,
      pi_nRightsMode      in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2
      )
   is
      v_vSql                               varchar2(4000);
      v_nCount                             number := 0;
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
   
      v_vSql := 'select count(*) from tbicds.fx_rights_template t where t.user_type = :P0';
      execute immediate v_vSql into v_nCount using pi_nUserType;
   
      if v_nCount > 0 then
         UpdateRightsTemplate(pi_vSessionID => pi_vSessionID,
                              pi_vSessionClientIP => pi_vSessionClientIP, 
                              pi_nUserID => pi_nUserID,
                              pi_nUserType => pi_nUserType,
                              pi_nUserRights => pi_nUserRights,
                              pi_nRightsMode => pi_nRightsMode,
                              po_nStatusCode => po_nStatusCode, 
                              po_vStatusComment => po_vStatusComment);
      else
         v_vSql := 'insert into tbicds.fx_rights_template (user_type, user_rights, read_only) '
                   || 'values (:P0, :P1, :P2)';
         execute immediate v_vSql using pi_nUserType, pi_nUserRights, pi_nRightsMode;
         commit;
      end if;
   
   exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_AP_USERADMIN.InsertRightsTemplate(): ' ||
                           sqlErrm;
   end;
   
   /*update rights template*/
   procedure UpdateRightsTemplate (
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      pi_nUserType        in number,
      pi_nUserRights      in number,
      pi_nRightsMode      in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2
      )
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'update tbicds.fx_rights_template t set '
                || 't.user_rights = :P0, t.read_only = :P1 '
                || 'where t.user_type = :P2';
      execute immediate v_vSql using pi_nUserRights, pi_nRightsMode, pi_nUserType;
      commit;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_AP_USERADMIN.UpdateRightsTemplate(): ' || sqlErrm;
   end;
   
   /*get rights template recordset*/
   procedure GetRightsTemplateRS (
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2,
      rs                  out sys_refcursor
      )
   is
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      open rs for 'select * from tbicds.fx_rights_template t';

   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_AP_USERADMIN.GetRightsTemplateRS(): ' || sqlErrm;
   end;

end;
/

prompt
prompt Creating package body PCK_COMMON
prompt ================================
prompt
create or replace package body tbicds.PCK_COMMON is

  /* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  /*****
  helper function used to get age given date of birth
  *****/
  function GetAge(pi_dtDOB in date) return number 
  is
    v_nAge number;
  begin
    v_nAge := trunc(months_between(sysdate, pi_dtDOB) / 12);
    return v_nAge;
  end;

  /*
  get a piece of data from a string given the delimeter and position
  */
  function GetPiece(strData      in varchar2,
                    strDelimiter in varchar2,
                    nPosition    in NUMBER) return varchar2 
  is
  
    strWorking varchar2(4000);
    strPiece   varchar2(400);
    pos        number;
    nPos2      number;
    nCount     number;
  begin
    --the piece to return
    strPiece := '';
  
    --set working to data
    strWorking := strData;
  
    --put a delimeter on the front for parsing if needed
    if substr(strWorking, 1, 1) != strDelimiter then
      strWorking := strDelimiter || strWorking;
    end if;
  
    --put a delimeter on the end
    strWorking := strWorking || strDelimiter;
  
    --find the piece between the ~'s ie... "~piece~"
    pos    := -1;
    nCount := -1;
    while (pos != 0) loop
      pos := instr(strWorking, strDelimiter);
      if pos != 0 then
        --increment count
        nCount := nCount + 1;
        --found the piece...
        if nCount = nPosition then
          if (pos + 1 > length(strWorking) - 1) then
            --nothing
            strPiece := '';
          else
            strWorking := substr(strWorking, pos + 1);
            nPos2      := instr(strWorking, strDelimiter);
            if nPos2 = 0 then
              --last piece
              strPiece := strWorking;
              return ltrim(rtrim(strPiece));
            else
              strPiece := substr(strWorking, 0, nPos2 - 1);
              return ltrim(rtrim(strPiece));
            end if;
          end if;
        else
          strWorking := substr(strWorking, pos + 1);
        end if;
      end if;
    end loop;
  
    return ltrim(rtrim(strPiece));
  
  exception
    when others then
      return '';
  end GetPiece;

  /*join data together by delimeter and return*/ 
  function join(p_cursor sys_refcursor, p_del varchar2 := ',')
    return varchar2 
  is
    l_value  varchar2(32767);
    l_result varchar2(32767);
  begin
    loop
      fetch p_cursor into l_value;
      exit when p_cursor%notfound;
      if l_result is not null then
        l_result := l_result || p_del;
      end if;
      l_result := l_result || l_value;
    end loop;
    return l_result;
  end join;

end;
/

prompt
prompt Creating package body PCK_CPA
prompt =============================
prompt
create or replace package body tbicds.PCK_CPA is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/******
delete an event
******/  
procedure DeleteEvent (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
    
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is
    v_nTemp number := 0;
    
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    delete from pat_pw_event_entry t 
    where t.pat_pw_event_id = pi_nPatPWEventID;
    commit;
    
    delete from pat_pw_event_module t 
    where t.pat_pw_event_id = pi_nPatPWEventID;
    commit;
    
    delete from pat_pw_event t 
    where t.pat_pw_event_id = pi_nPatPWEventID;
    commit;
    
    update pat_pw_event set
      plan_pat_pw_event_id = null
    where plan_pat_pw_event_id = pi_nPatPWEventID;
    commit;
    
exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;



/******
Check if the user can delete the event
******/  
procedure AllowEventDelete (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
         
      po_nAllowDelete           out number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is
    v_nTemp number := 0;
    
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    po_nAllowDelete := 1;
   
    --check the status 2 = event is closed
    select t.status into v_nTemp 
    from pat_pw_event t
    where t.pat_pw_event_id = pi_nPatPWEventID;
    if v_nTemp = 2 then
       po_nAllowDelete := 0;
       return;  
    end if;
    
    --check if the event has any completed instruments
    select count(*) into v_nTemp  
    from pat_pw_event_module t
    where t.pat_pw_event_id = pi_nPatPWEventID
    and nvl(t.intake_id,0) > 0;
    if v_nTemp > 0 then
       po_nAllowDelete := 0;
       return;  
    end if;

    --check if the event has any note text
    select count(*) into v_nTemp  
    from pat_pw_event t
    where t.pat_pw_event_id = pi_nPatPWEventID
    and t.note_text is not null
    and length( nvl(t.note_text,'') ) > 0;
    if v_nTemp > 0 then
       po_nAllowDelete := 0;
       return;  
    end if;

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/****
insert a new pat pw event
***/
procedure InsertPatPWEvent (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
   
      pi_vEventTitle            in varchar2,
      pi_dtEventDate            in date,
      pi_nAdjustFuture          in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is
      v_nPatPWEventID number := 0;
   
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --get a new patient pathway event id
    select SEQPATPWEVENTID.nextval into v_nPatPWEventID from dual;
    
    --insert the event 
    insert into pat_pw_event
                (PATIENT_ID,
                 STATUS,
                 DATE_SCHEDULED,
                 DATE_STARTED,
                 DATE_COMPLETED,
                 REGION_ID,
                 SITE_ID,
                 PAT_PW_ID,
                 EVENT_TITLE,
                 EVENT_DESCR,
                 SORT_ORDER,
                 EVENT_FREQUENCY,
                 PW_EVENT_TYPE_ID,
                 PAT_PW_EVENT_ID,
                 CREATED_BY)
        values(pi_vPatientID,
               0,
               pi_dtEventDate,
               null,
               null,
               pi_nRegionID,
               pi_nSiteID,
               pi_nPatPWID,
               pi_vEventTitle,
               '',
               99,
               null,
               1, --scheduled
               v_nPatPWEventID,
               pi_nUserID);
        
        commit;                  
        
        --update the event just created to allow for adjust
        if pi_nAdjustFuture = 1 then
          
          UpdatePatPWEvent( pi_vSessionID,
                            pi_vSessionClientIP,
                            pi_nUserID,
                            pi_vPatientID,
                            v_nPatPWEventID,
                            
                            pi_vEventTitle,
                            pi_dtEventDate,
                            pi_nAdjustFuture,
                            
                            po_nStatusCode,
                            po_vStatusComment);
          commit;
        
        end if;
        
exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/***
Update the pw event info
****/
procedure UpdatePatPWEvent (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      
      pi_vEventTitle            in varchar2,
      pi_dtEventDate            in date,
      pi_nAdjustFuture          in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

      v_nIndex number := 0;
      
      v_dtOldScheduled date := null;
      v_nPatPWID number := 0;
      v_nDays number := 0;
      v_nEventModuleID number := 0;
   
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    v_nEventModuleID := 0;
    
    --keep the original date for calculations
    select date_scheduled, pat_pw_id 
    into v_dtOldScheduled, v_nPatPWID
    from pat_pw_event 
    where pat_pw_event_id = pi_nPatPWEventID
    and patient_id = pi_vPatientID;
    
    --update title and date
    update pat_pw_event 
    set event_title = pi_vEventTitle,
        date_scheduled = pi_dtEventDate
    where pat_pw_event_id = pi_nPatPWEventID
    and patient_id = pi_vPatientID;
    commit;
        
    --get the number of days this date is different    
    if pi_nAdjustFuture = 1 then
       
       --get the date diff 
       SELECT trunc(pi_dtEventDate)- (v_dtOldScheduled) 
         into v_nDays 
         FROM DUAL;
             
       --update all events after this event
       /*update pat_pw_event pe
          set pe.date_scheduled =  pe.date_scheduled + v_nDays
        where patient_id = pi_vPatientID
          --and pe.pat_pw_event_id > pi_nPatPWEventID
          and pe.date_scheduled > pi_dtEventDate 
          and pe.date_completed is null 
          and pe.pat_pw_id = pat_pw_id; */
       update pat_pw_event pe
          set pe.date_scheduled =  pe.date_scheduled + v_nDays
        where patient_id = pi_vPatientID
          and pe.pat_pw_event_id > pi_nPatPWEventID
          and pe.pat_pw_id = pat_pw_id;
       commit;         
      
    end if;
       
    commit;

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;



/*delete a scheduled module*/
procedure DeletePatPWEventModules (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      pi_vMIDS                  in varchar2,
     
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

      v_nIndex number := 0;
      v_vMIDPiece varchar2(4000) := ''; 
      v_nMID number := 0;   
      v_nModuleFor number := 2;
      
      v_dtOldScheduled date := null;
      v_nPatPWID number := 0;
      v_nDays number := 0;
      v_nEventModuleID number := 0;
   
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    v_nEventModuleID := 0;
    
     --loop and add modules
     loop
      
      --get one mid   
      v_vMIDPiece := pck_common.GetPiece(pi_vMIDs, ',' , v_nIndex);
      
      EXIT WHEN v_vMIDPiece is null;
            
      begin
        
           --get the mid and bump the index
           v_nMID := to_number(v_vMIDPiece);
           v_nIndex := v_nIndex +1;
           
           --only delete modules that do not have and intake_id
           delete from pat_pw_event_module t
           where t.patient_id = pi_vPatientID 
           and t.pat_pw_event_id = pi_nPatPWEventID 
           and nvl(t.intake_id,0) <= 0 
           and t.mid = v_nMID;
                                    
           commit;                                 
      
      exception
      when others then
           null;
      end;
      
     end loop;
       
    commit;

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Gets all pathway event modules associated 
with a specific patient pathway event
******/
procedure GetPWEventModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID             in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(2000) :=
      'SELECT t.*,
              t3.module, 
              t3.description, 
              t3.module_alt_lang, 
              t3.description_alt_lang, 
              t3.acronym, 
              t3.score_logic,
              
              (select nvl(tt.status,0) from
                pat_pw_event tt
                where tt.pat_pw_event_id = :PAT_PW_EVENT_ID) 
                as event_status     
              
       FROM tbicds.PAT_PW_EVENT_MODULE t,
            tbicds.intake_module t3 
            
       WHERE t.patient_id = :PATIENT_ID 
         and t.PAT_PW_EVENT_ID = :PW_EVENT_ID 
         and t3.mid = t.mid
      
       ORDER BY t.sort_order ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_nPatPWEventID,
          pi_vPatientID,
          pi_nPatPWEventID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/***
insert modules into the pat pw event module list
****/
procedure InsertPatPWEventModules (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      pi_vMIDS                  in varchar2,
      pi_vModuleFors            in varchar2,
     
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

      v_nIndex number := 0;
      v_vMIDPiece varchar2(4000) := ''; 
      v_vFORPiece varchar2(4000) := '';  
      v_nMID number := 0;   
      v_nModuleFor number := 2;
      
      v_dtOldScheduled date := null;
      v_nPatPWID number := 0;
      v_nDays number := 0;
      v_nEventModuleID number := 0;
   
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    v_nEventModuleID := 0;
    
     --loop and add modules
     loop
      
      --get one mid   
      v_vMIDPiece := pck_common.GetPiece(pi_vMIDs, ',' , v_nIndex);
      
      --get one module for
      v_vFORPiece := pck_common.GetPiece(pi_vModuleFors, ',' , v_nIndex);
      
      EXIT WHEN v_vMIDPiece is null;
            
      begin
        
           --get the mid and bump the index
           v_nMID := to_number(v_vMIDPiece);
           v_nModuleFor := to_number(v_vFORPiece);
           v_nIndex := v_nIndex +1;
           
           select SEQPATPWEVENTMODULEID.Nextval 
           into v_nEventModuleID from dual;
           
           insert into 
           pat_pw_event_module(PATIENT_ID,
                               MID,
                               STATUS,
                               REGION_ID,
                               SITE_ID,
                               DATE_STARTED,
                               DATE_COMPLETED,
                               PAT_PW_ID,
                               INTAKE_ID,
                               MODULE_FOR,
                               SORT_ORDER,
                               PAT_PW_EVENT_ID,
                               DATE_SCHEDULED,
                               PW_EVENT_MODULE_ID)
            values(pi_vPatientID,
                   
                   v_nMID,
                   
                   0,--status
                   
                   (select REGION_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                   
                    (select SITE_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                    
                    null, --date started
                    
                    null, --date completed
                   
                   (select PAT_PW_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                   
                    null, --intake_id
                    
                    v_nModuleFor, --module for
                    
                    (select nvl(max(sort_order), 0) + 1 
                       from pat_pw_event_module 
                      where pat_pw_event_id = pi_nPatPWEventID),
                      
                    pi_nPatPWEventID,
                    
                    sysdate,
                    
                    v_nEventModuleID);
                                    
           commit;                                 
           
      
      exception
      when others then
           null;
      end;
      
     end loop;
       
    commit;

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*****
Gets all clinical program area types
******/
procedure GetCPATypeRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*
       FROM tbicds.CPA_Type t 
       ORDER BY upper(t.sort_order) ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs for v_vSQL;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*****
Gets all clinical program areas by region/site
******/
procedure GetCPARS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*
       FROM tbicds.CPA t,
            tbicds.CPA_TYPE t2
       WHERE t.region_id = :REGION_ID
       and t.site_id = :SITE_ID 
       and t.CPA_TYPE_ID = t2.CPA_TYPE_ID 
       ORDER BY t2.sort_order ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL
      using pi_nRegionID, pi_nSiteID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Gets all pathways for a clinical program area 
each site has its own list of clinical program areas
******/
procedure GetCPAPWRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nCPAID                 in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*
       FROM tbicds.CPA_PW t 
       WHERE CPA_ID = :CPA_ID
       ORDER BY upper(t.PW_TITLE) ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL
      using pi_nCPAID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Gets all pathway events for a pathway
******/
procedure GetPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nPWID                  in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*
       FROM tbicds.CPA_PW_EVENT t 
       WHERE PW_ID = :PW_ID
       ORDER BY t.sort_order ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL
      using pi_nPWID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*****
Gets all modules for a pathway event
******/
procedure GetPWEventModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nPWID                  in number,
      pi_nPWEventID             in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*, 
              t2.module, 
              t2.description, 
              t2.module_alt_lang, 
              t2.description_alt_lang, 
              t2.acronym, 
              t2.score_logic 
       FROM tbicds.CPA_PW_EVENT_MODULE t,
            tbicds.intake_module t2 
       WHERE PW_ID = :PW_ID
       and PW_EVENT_ID = :PW_EVENT_ID
       and t.mid = t2.mid
       ORDER BY t.sort_order ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL
      using pi_nPWID,
            pi_nPWEventID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*****
Gets all events and modules for a pathway 
******/
procedure GetPWEventAndModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nPWID                  in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'select * 
        from cpa_pw_event t1,
             cpa_pw_event_module t2,
             intake_module t3
        where t1.cpa_id = t2.cpa_id(+)
          and t1.pw_event_id = t2.pw_event_id(+)
          and t1.pw_id = t2.pw_id(+)
          and t2.mid = t3.mid(+)
          and t1.pw_id = :PW_ID   
        order by t1.sort_order ';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL
      using pi_nPWID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;




----USER tables------------------------------------------------------

/*****
update a users default clinical program area
******/
procedure UpdateUserDefaultCPA (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nCPAID                 in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

     v_vSQL varchar2(500) :=
      'UPDATE tbicds.fx_user 
       set default_cpa_id = :cpa_id
       where fx_user_id = :user_id';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --execute the sql
    execute immediate v_vSQL 
                using pi_nUserID,
                      pi_nCPAID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Gets a users clinical program areas
******/
procedure GetUserCPARS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1024) :=
      'SELECT t.*,
              
              (select count(*) 
                 from tbicds.fx_user
                where default_cpa_id = t.cpa_id
                and fx_user_id = :FX_USER_ID) as default_cpa_id
                
         FROM tbicds.CPA t
         
        where t.region_id = (select region_id 
                            from tbicds.fx_user 
                            where fx_user_id = :FX_USER_ID)
                             
          and t.site_id = (select site_id 
                            from tbicds.fx_user 
                            where fx_user_id = :FX_USER_ID)
                            
       ORDER BY upper(t.cpa_title) ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL 
    using pi_nUserID,
          pi_nUserID,
          pi_nUserID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;
 
-------patient tables ----------------------------------------------


/*****
Gets all pathways associated with a patient, 
ordered by region, site and clinical program area
******/
procedure GetPatPWRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
        'SELECT t.*
       FROM tbicds.PAT_PW t
       WHERE t.patient_id = :PATIENT_ID 
       ORDER BY t.region_id, 
                t.site_id,
                t.date_created DESC';
       
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*Check if the Event is Read-Only*/
procedure IsPatPWEventReadOnly (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
      pi_nPatPWEventID          in number,
      po_nIsReadOnly            out number, --0 = False = Is Not Read Only; 1 = True = Is Read Only 
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

  v_nIsReadOnly number := 1; --TRUE

begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    begin
      select 
        case nvl(t.status,0) 
          when 2 then 1 --TRUE = Is Read Only
          else 0 --FALSE = Is Not Read Only
        end            
        into v_nIsReadOnly
      from pat_pw_event t
      where t.patient_id = pi_vPatientID
        and t.pat_pw_id = pi_nPatPWID
        and t.pat_pw_event_id = pi_nPatPWEventID;
    exception
      when others then
        v_nIsReadOnly := 1;
    end;
    
    po_nIsReadOnly := v_nIsReadOnly;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Gets all pathway events for a specific patient pathway
******/
procedure GetPatPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWID                  in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'SELECT  t.PATIENT_ID,	
                t.STATUS,
                t.DATE_SCHEDULED,
                t.DATE_STARTED,
                t.DATE_COMPLETED,
                t.REGION_ID,
                t.SITE_ID,
                t.PAT_PW_ID,
                t.PLAN_TEXT,
                t.PLAN_PAT_PW_EVENT_ID,
               
       decode(trim(event_title),
                                 null,

                decode(t.date_completed,
                       null,
                       '''' || to_char(date_scheduled, ''MM/DD/YYYY'' ), 
                       '''' || to_char(date_completed, ''MM/DD/YYYY'')
                       ),
                       
                decode(t.date_completed,
                       null,
                       '''' || to_char(date_scheduled, ''MM/DD/YYYY'') || '' - ('' || event_title || '')'', 
                       '''' || to_char(date_completed, ''MM/DD/YYYY'') || '' - ('' || event_title || '')''
                       ) ) as event_title,
                       
                t.EVENT_DESCR,
                t.SORT_ORDER,
                t.EVENT_FREQUENCY,
                t.PW_EVENT_TYPE_ID,
                t.PAT_PW_EVENT_ID
       
       FROM tbicds.PAT_PW_EVENT t
       WHERE t.patient_id = :PATIENT_ID 
       and t.pat_pw_id = :PAT_PW_ID
       ORDER BY nvl(t.DATE_COMPLETED,t.DATE_SCHEDULED) ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID,
          pi_nPatPWID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Gets all pathway events associated with a patient
******/
procedure GetPatPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1500) :=
       
        'SELECT  t.PATIENT_ID,	
                t.STATUS,
                t.DATE_SCHEDULED,
                t.DATE_STARTED,
                t.DATE_COMPLETED,
                t.REGION_ID,
                t.SITE_ID,
                t.PAT_PW_ID,
                t.PLAN_TEXT,
                t.PLAN_PAT_PW_EVENT_ID,
               
                decode(trim(event_title),
                                 null,

                decode(t.date_completed,
                       null,
                       '''' || to_char(date_scheduled, ''MM/DD/YYYY'' ), 
                       '''' || to_char(date_completed, ''MM/DD/YYYY'')
                       ),
                       
                decode(t.date_completed,
                       null,
                       '''' || to_char(date_scheduled, ''MM/DD/YYYY'') || '' - ('' || event_title || '')'', 
                       '''' || to_char(date_completed, ''MM/DD/YYYY'') || '' - ('' || event_title || '')''
                       ) ) as event_title,
       
                t.EVENT_DESCR,
                t.SORT_ORDER,
                t.EVENT_FREQUENCY,
                t.PW_EVENT_TYPE_ID,
                t.PAT_PW_EVENT_ID

       FROM tbicds.PAT_PW_EVENT t
       WHERE t.patient_id = :PATIENT_ID 
         ORDER BY t.DATE_SCHEDULED ASC';
       
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Gets one pathway event associated with a patient
******/
procedure GetPatPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1500) :=
       
        'SELECT t.PATIENT_ID,	
                t.STATUS,
                t.DATE_SCHEDULED,
                t.DATE_STARTED,
                t.DATE_COMPLETED,
                t.REGION_ID,
                t.SITE_ID,
                t.PAT_PW_ID,
                t.event_title,
                t.EVENT_DESCR,
                t.SORT_ORDER,
                t.EVENT_FREQUENCY,
                t.PW_EVENT_TYPE_ID,
                t.PAT_PW_EVENT_ID,
                t.PLAN_PAT_PW_EVENT_ID,
                t.PLAN_TEXT,
                t.NOTE_TEXT,
                t.TIU_DFN,
                t.TIU_DUZ,
                t.TIU_ENCOUNTER_ID,
                t.TIU_CONSULT_IEN,
                t.TIU_COSIGNER_DUZ,
                t.TIU_NOTE_TITLE_IEN,
                t.TIU_NOTE,
                t.TIU_CLINIC_ID,
                t.TIU_DATE_SUBMITTED,
                t.TIU_ENCOUNTER_TYPE,
                t.TIU_NOTE_TITLE,
                t.TIU_LOCATION,
                t.TIU_COSIGNER,
                t.TIU_NOTE_ID,
                t.TIU_CONSULT
                
       FROM tbicds.PAT_PW_EVENT t
       WHERE t.patient_id = :PATIENT_ID 
         and t.pat_pw_event_id = :PAT_PW_EVENT_ID 
         ORDER BY t.DATE_SCHEDULED ASC';
       
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID,
          pi_nPatPWEventID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;




/*****
Gets all pathway event modules associated 
with a specific patient pathway event
******/
procedure GetPatPWEventModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
      pi_nPatPWEventID             in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1000) :=
      'SELECT t.*,
              t3.module, 
              t3.description, 
              t3.module_alt_lang, 
              t3.description_alt_lang, 
              t3.acronym, 
              t3.score_logic,
              
              (select nvl(tt.status,0) from
                pat_pw_event tt
                where tt.pat_pw_event_id = :PAT_PW_EVENT_ID) 
                as event_status     
              
       FROM tbicds.PAT_PW_EVENT_MODULE t,
            tbicds.intake_module t3 
            
       WHERE t.patient_id = :PATIENT_ID 
         and t.PAT_PW_ID  = :PAT_PW_ID 
         and t.PAT_PW_EVENT_ID = :PW_EVENT_ID 
         
         and t3.mid = t.mid
         
       ORDER BY t.sort_order ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_nPatPWEventID,
          pi_vPatientID,
          pi_nPatPWID,
          pi_nPatPWEventID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*get all modules for a patient pw event*/
procedure GetPatPWEventModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID             in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1000) :=
      'SELECT t.*,
              t3.module, 
              t3.description, 
              t3.module_alt_lang, 
              t3.description_alt_lang, 
              t3.acronym, 
              t3.score_logic   
              
       FROM tbicds.PAT_PW_EVENT_MODULE t,
            tbicds.intake_module t3 
            
       WHERE t.patient_id = :PATIENT_ID 
         and t.PAT_PW_EVENT_ID = :PW_EVENT_ID 
         
         and t3.mid = t.mid
         
       ORDER BY t.sort_order ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID,
          pi_nPatPWEventID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Gets all pathway event modules associated with a patient 
******/
procedure GetPatPWEventModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1000) :=
       'SELECT t.*, 
              
              t3.module, 
              t3.description, 
              t3.module_alt_lang, 
              t3.description_alt_lang, 
              t3.acronym, 
              t3.score_logic   
              
       FROM tbicds.PAT_PW_EVENT_MODULE t,
            tbicds.intake_module t3 
            
       WHERE t.patient_id = :PATIENT_ID 
         
         and t3.mid = t.mid
         
       ORDER BY t.pat_pw_id, t.pat_pw_event_id, t.sort_order ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

-------------------------------TODO: operations--------------------------------

procedure ApplyDefaultPathway (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is
     v_nPatPWID   number := 0;
     v_nPWID      number := 0;
     v_nCPAID      number := 0;
     
     v_vSQL varchar2(4000) := '';

     v_vPWSelectSQL varchar2(1000) :=
        'select t.*
           from CPA_PW t
          where t.PW_ID = :PW_ID';  
          
     v_vPWEventSelectSQL varchar2(1000) :=
        'select t.*
           from CPA_PW_EVENT t 
          where t.PW_ID = :PW_ID
          order by sort_order asc';   
          
      v_vPWEventModuleSelectSQL varchar2(1000) :=
        'select t.*
           from CPA_PW_EVENT_MODULE t 
          where t.PW_ID = :PW_ID
          order by sort_order asc';    
          
      v_rsPWSelect  refCursor;
      v_rsPWEventSelect  refCursor;
      v_rsPWEventModuleSelect  refCursor;    
               
      v_recPWSelect  tbicds.cpa_pw%ROWTYPE;
      v_recPWEventSelect tbicds.cpa_pw_event%ROWTYPE;
      v_recPWEventModuleSelect tbicds.cpa_pw_event_module%ROWTYPE;
               
      v_nPatPWEventID number := 0;
      v_nCount number := 0;
      
      v_dtSched date := null;
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --the the one and only open pathway for this site
    select pw_id, cpa_id into v_nPWID, v_nCPAID from cpa_pw t
    where t.pw_type_id = 3
    and t.region_id = pi_nRegionID
    and t.site_id = pi_nSiteID 
    and rownum = 1;    
    
    --only apply if it doesnt exist!
    select count(*) into v_nCount 
    from pat_pw
    where patient_id = pi_vPatientID;
    
    if v_nCount > 0 then
      return;
    end if;
  
     --open the select recordsets
    open v_rsPWSelect for v_vPWSelectSQL using v_nPWID;
    open v_rsPWEventSelect for v_vPWEventSelectSQL using v_nPWID;
    open v_rsPWEventModuleSelect for v_vPWEventModuleSelectSQL using v_nPWID;
    
    --get a new patient pathway id
    select SEQPATPWID.nextval into v_nPatPWID from dual;
    
    --loop and copy pathway, should only be onw record
    LOOP
         v_recPWSelect := null;
         FETCH v_rsPWSelect INTO v_recPWSelect;
         EXIT WHEN NOT v_rsPWSelect%found;
  
         --add a record to the patient pathway table
         insert into tbicds.pat_pw
                (PATIENT_ID,
                 DATE_CREATED,
                 CREATED_BY,
                 STATUS,
                 PW_TYPE_ID,
                 REGION_ID,
                 SITE_ID,
                 PAT_PW_ID,
                 PW_TITLE,
                 PW_DESCR,
                 PW_ID,
                 CPA_ID)
         values(pi_vPatientID,
                sysdate,
                pi_nUserID,
                1, --1 = open
                v_recPWSelect.pw_type_id,
                v_recPWSelect.region_id,
                v_recPWSelect.site_id,
                v_nPatPWID,
                v_recPWSelect.pw_title,
                v_recPWSelect.pw_descr,
                v_nPWID,
                v_nCPAID);         
         
         commit;                             

    END LOOP;
    CLOSE v_rsPWSelect;
    
    --get a new patient pathway id
    select SEQPATPWEVENTID.nextval into v_nPatPWEventID from dual;
    v_dtSched := sysdate;
          
    --loop and copy pathway event
    LOOP
         v_recPWEventSelect := null;
         FETCH v_rsPWEventSelect INTO v_recPWEventSelect;
         EXIT WHEN NOT v_rsPWEventSelect%found;
         
         
         
         insert into pat_pw_event
                (PATIENT_ID,
                 STATUS,
                 DATE_SCHEDULED,
                 DATE_STARTED,
                 DATE_COMPLETED,
                 REGION_ID,
                 SITE_ID,
                 PAT_PW_ID,
                 EVENT_TITLE,
                 EVENT_DESCR,
                 SORT_ORDER,
                 EVENT_FREQUENCY,
                 PW_EVENT_TYPE_ID,
                 PAT_PW_EVENT_ID,
                 CREATED_BY)
        values(pi_vPatientID,
               0,
               v_dtSched,
               null,
               null,
               v_recPWEventSelect.REGION_ID,
               v_recPWEventSelect.SITE_ID,
               v_nPatPWID,
               --v_recPWEventSelect.EVENT_TITLE,
               --to_char(v_dtSched),
               '', --no title for default pathway
               v_recPWEventSelect.EVENT_DESCR,
               v_recPWEventSelect.SORT_ORDER,
               v_recPWEventSelect.EVENT_FREQUENCY,
               v_recPWEventSelect.PW_EVENT_TYPE_ID,
               v_nPatPWEventID,
               pi_nUserID);
        
        commit;                  

    END LOOP;
    CLOSE v_rsPWEventSelect;
        
    --no modules for open pathway
    
    commit;

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*
merge pathway events and modules
*/
procedure MergePathwayEvents (
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
      po_nMerged                out number
      )
is
      v_rsPatPWEvent  refCursor; 
      v_recPatPWEvent tbicds.pat_pw_event%ROWTYPE;
      v_nCount number := 0;
begin

    po_nMerged := 0;
       
    --update the base pathway (the first selected), 
    --move all mids from others matching freq and delete
    --the merged events and modules
    --MERGED = 1 moves to MERGED = 2
    open v_rsPatPWEvent for
    
          select * from PAT_PW_EVENT t 
          where pat_pw_id = pi_nPatPWID
          and MERGED = 1
          and patient_id = pi_vPatientID
          order by event_frequency asc; 
          
     LOOP
         --fetch a record for work   
         v_recPatPWEvent := null;
         FETCH v_rsPatPWEvent INTO v_recPatPWEvent;
         EXIT WHEN NOT v_rsPatPWEvent%found;
         
         begin
           
           insert into pat_pw_event_module
                   (PATIENT_ID,
                    MID,
                    STATUS,
                    REGION_ID,
                    SITE_ID,
                    DATE_STARTED,
                    DATE_COMPLETED,
                    PAT_PW_ID,
                    INTAKE_ID,
                    MODULE_FOR,
                    SORT_ORDER,
                    PAT_PW_EVENT_ID,
                    DATE_SCHEDULED,
                    merged,
                    PW_EVENT_MODULE_ID) 
         
           (select pem.PATIENT_ID,
                   pem.MID,
                   pem.STATUS,
                   pem.REGION_ID,
                   pem.SITE_ID,
                   pem.DATE_STARTED,
                   pem.DATE_COMPLETED,
                   pem.PAT_PW_ID,
                   pem.INTAKE_ID,
                   pem.MODULE_FOR,
                   9999 as SORT_ORDER,
                   v_recPatPWEvent.PAT_PW_EVENT_ID as PAT_PW_EVENT_ID,
                   pem.DATE_SCHEDULED,
                   1 as merged,
                   pem.PW_EVENT_MODULE_ID
                   
              from pat_pw_event_module pem
              
             where pem.pat_pw_id = pi_nPatPWID
             
               and pem.patient_id = pi_vPatientID
               
               and pem.pat_pw_event_id 
                   in (select pat_pw_event_id
                         from pat_pw_event ppe
                        where ppe.pat_pw_id = pi_nPatPWID
                          and ppe.patient_id = pi_vPatientID
                          and ppe.MERGED = 0 
                          and ppe.event_frequency = v_recPatPWEvent.event_frequency
                       ));
             commit;                   
       
           exception
           when others then 
             --dupes wont go but thats ok so press on
             null;
           end;
           
           
           --delete all dupes
           delete 
           from PAT_PW_EVENT_MODULE a
           where pat_pw_id = pi_nPatPWID
             and patient_id = pi_vPatientID
             and PAT_PW_EVENT_ID = v_recPatPWEvent.PAT_PW_EVENT_ID
             and a.rowid > 
             any 
               (select b.rowid from PAT_PW_EVENT_MODULE b
                 where pat_pw_id = pi_nPatPWID
                 and patient_id = pi_vPatientID
                 and PAT_PW_EVENT_ID = v_recPatPWEvent.PAT_PW_EVENT_ID
                 and a.mid = b.mid);
      
     END LOOP;
    
     --first pass done so now delete processed records
     --delete the modules merged
     delete from pat_pw_event_module t
     where t.pat_pw_id = pi_nPatPWID
     and patient_id = pi_vPatientID
     and pat_pw_event_id in 
          (select pat_pw_event_id
            from pat_pw_event
           where pat_pw_id = pi_nPatPWID
             and patient_id = pi_vPatientID
             and MERGED = 0 
             and event_frequency in
             ( select event_frequency
               from pat_pw_event
               where MERGED = 1 
               and pat_pw_id = pi_nPatPWID
               and patient_id = pi_vPatientID));
      commit;
      
      --delete the events merged 
      delete from pat_pw_event t
      where t.pat_pw_id = pi_nPatPWID
      and patient_id = pi_vPatientID
      and pat_pw_event_id in 
          (select pat_pw_event_id
            from pat_pw_event
           where pat_pw_id = pi_nPatPWID
             and patient_id = pi_vPatientID
             and MERGED = 0 
             and event_frequency in
             ( select event_frequency
               from pat_pw_event
               where MERGED = 1 
               and pat_pw_id = pi_nPatPWID
               and patient_id = pi_vPatientID));
       commit;
       
       --now mark the merged base to 2
       --2 means all merged so dont have to process anymore
       update pat_pw_event t
       set t.MERGED = 2
       where t.pat_pw_id = pi_nPatPWID
       and patient_id = pi_vPatientID
       and t.MERGED = 1;
       commit;
       
       --now update for the next set to merge
       update PAT_PW_EVENT pe
       set pe.merged = 1 
       where pe.pat_pw_id = pi_nPatPWID
         and pe.patient_id = pi_vPatientID
          
         and pe.event_frequency in 
             (select t.event_frequency 
                 from PAT_PW_EVENT t 
                where t.pat_pw_id = pi_nPatPWID
                  and t.patient_id = pi_vPatientID
                  and t.merged != 2
                 
                  and (select count(*) 
                         from PAT_PW_EVENT t2 
                        where t2.pat_pw_id = pi_nPatPWID
                          and t2.patient_id = pi_vPatientID
                          and t2.merged != 2
                          and t2.event_frequency = t.event_frequency 
                     group by t2.event_frequency) > 1 )
         
         and rownum = 1;
         commit;
  
       
       --do we still have work to do?
       select count(*) into v_nCount
       from pat_pw_event t 
       where t.pat_pw_id = pi_nPatPWID
       and t.patient_id = pi_vPatientID
       and t.MERGED = 1;
       
       if v_nCount < 1 then
         po_nMerged := 1; --all done
       else
         po_nMerged := 0; --more to do
       end if;
       
exception
    when others then
      rollback;
      po_nMerged := 1;
      
end;

/******
apply a pathway/schedule to a patient
******/  
procedure ApplyPathway (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      
      pi_vPWIDs                 in varchar2,
      pi_vPWTitle               in varchar2,
      pi_dtBaseline             in date,
      
      po_nPatPWID               out number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is
     v_nPatPWID   number := 0;
     
     v_vSQL varchar2(4000) := '';

     v_vPWSelectSQL varchar2(1000) :=
        'select t.*
           from CPA_PW t
          where t.PW_ID = :PW_ID';  
          
     v_vPWEventSelectSQL varchar2(1000) :=
        'select t.*
           from CPA_PW_EVENT t 
          where t.PW_ID = :PW_ID 
          order by sort_order asc';  
       
          
      v_vPWEventModuleSelectSQL varchar2(1000) :=
        'select t.*
           from CPA_PW_EVENT_MODULE t 
          where t.PW_ID = :PW_ID
          order by sort_order asc';    
          
      v_rsPWSelect  refCursor;
      v_rsPWEventSelect  refCursor;
      v_rsPWEventModuleSelect  refCursor;  
      
      v_rsPatPWEvent  refCursor; 
      v_recPatPWEvent tbicds.pat_pw_event%ROWTYPE;
       
      
      v_recPWSelect  tbicds.cpa_pw%ROWTYPE;
      v_recPWEventSelect tbicds.cpa_pw_event%ROWTYPE;
      v_recPWEventModuleSelect tbicds.cpa_pw_event_module%ROWTYPE;
    
      v_nCPAID number := 0;  
      v_nPWID number := 0;       
      v_nPatPWEventID number := 0;  
      
      v_dtScheduled date := null;
      v_nEventFrequency number := 0;
      v_nIndex number := 0;
      v_vPiece varchar2(4000) := '';
      
      v_nPWRecordInserted number := 0;
     
      --fisrt pw_id is always the master for combining
      v_nMaster number := 0;
      v_nMerged number := 0;
      
      v_nEventModuleID number := 0;
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    po_nPatPWID := 0;
    v_nPWID := 0;
    
    
    --get a new patient pathway id
    select SEQPATPWID.nextval into v_nPatPWID from dual;
      
    loop
      
      --get one pathway id   
      v_vPiece := pck_common.GetPiece(pi_vPWIDs, ',' , v_nIndex);
      EXIT WHEN v_vPiece is null;
      
      --bump the index
      v_nIndex := v_nIndex + 1;
    
      --convert the piece to a PW_ID number
      v_nPWID := to_number(v_vPiece);
      
      --get the cpa id
      select cpa_id into v_nCPAID
      from cpa_pw cp
      where cp.pw_id = v_nPWID;      
    
      --open the select recordsets
      open v_rsPWSelect for v_vPWSelectSQL using v_nPWID;
      open v_rsPWEventSelect for v_vPWEventSelectSQL using v_nPWID;
       
      --first record in list is used for pw insert
      v_recPWSelect := null;
      FETCH v_rsPWSelect INTO v_recPWSelect;
      if v_nPWRecordInserted = 0 then 
        
         --add a record to the patient pathway table
         insert into tbicds.pat_pw
                  (PATIENT_ID,
                   DATE_CREATED,
                   CREATED_BY,
                   STATUS,
                   PW_TYPE_ID,
                   REGION_ID,
                   SITE_ID,
                   PAT_PW_ID,
                   PW_TITLE,
                   PW_DESCR,
                   CPA_ID,
                   PW_ID)
           values(pi_vPatientID,
                  sysdate,
                  pi_nUserID,
                  1, --1 = open
                  v_recPWSelect.pw_type_id,
                  v_recPWSelect.region_id,
                  v_recPWSelect.site_id,
                  v_nPatPWID,
                  pi_vPWTitle,
                  v_recPWSelect.pw_descr,
                  v_nCPAID,
                  v_nPWID);         
           
           commit;           
           v_nPWRecordInserted := 1;
           v_nMaster := 1;
      else
           v_nMaster := 0;
      end if;
      CLOSE v_rsPWSelect;
      
      --loop and copy pathway event
      LOOP
           --fetch a record for work   
           v_recPWEventSelect := null;
           FETCH v_rsPWEventSelect INTO v_recPWEventSelect;
           EXIT WHEN NOT v_rsPWEventSelect%found;
           
           --get a new patient pathway id
           select SEQPATPWEVENTID.nextval into v_nPatPWEventID from dual;
           
           --calculate the estimated schedule date based 
           --on the baseline and interval
           v_dtScheduled := null;
           v_nEventFrequency := v_recPWEventSelect.EVENT_FREQUENCY;
           if v_nEventFrequency > 0 then
              v_dtScheduled := pi_dtBaseline + v_nEventFrequency;
           else
              v_dtScheduled := pi_dtBaseline;
           end if;
           
           --insert the event
           insert into pat_pw_event
                  (PATIENT_ID,
                   STATUS,
                   DATE_SCHEDULED,
                   DATE_STARTED,
                   DATE_COMPLETED,
                   REGION_ID,
                   SITE_ID,
                   PAT_PW_ID,
                   EVENT_TITLE,
                   EVENT_DESCR,
                   SORT_ORDER,
                   EVENT_FREQUENCY,
                   PW_EVENT_TYPE_ID,
                   PAT_PW_EVENT_ID,
                   MERGED,
                   CREATED_BY)
          values(pi_vPatientID,
                 0,
                 v_dtScheduled,
                 null,
                 null,
                 v_recPWEventSelect.REGION_ID,
                 v_recPWEventSelect.SITE_ID,
                 v_nPatPWID,
                 v_recPWEventSelect.EVENT_TITLE,
                 v_recPWEventSelect.EVENT_DESCR,
                 v_recPWEventSelect.SORT_ORDER,
                 v_recPWEventSelect.EVENT_FREQUENCY,
                 v_recPWEventSelect.PW_EVENT_TYPE_ID,
                 v_nPatPWEventID,
                 v_nMaster,
                 pi_nUserID);
          
         commit;            
                   
         --loop and copy pathway event module
         open v_rsPWEventModuleSelect for v_vPWEventModuleSelectSQL using v_nPWID;
         LOOP
           v_recPWEventModuleSelect := null;
           FETCH v_rsPWEventModuleSelect INTO v_recPWEventModuleSelect;
           EXIT WHEN NOT v_rsPWEventModuleSelect%found;
    
         if v_recPWEventModuleSelect.PW_ID = v_recPWEventSelect.PW_ID
             and v_recPWEventModuleSelect.PW_EVENT_ID = v_recPWEventSelect.PW_EVENT_ID
         then   
           
           select SEQPATPWEVENTMODULEID.Nextval 
           into v_nEventModuleID from dual;
              
           insert into pat_pw_event_module
                  ( PATIENT_ID,
                    MID,
                    STATUS,
                    REGION_ID,
                    SITE_ID,
                    DATE_STARTED,
                    DATE_COMPLETED,
                    PAT_PW_ID,
                    INTAKE_ID,
                    MODULE_FOR,
                    SORT_ORDER,
                    DATE_SCHEDULED,
                    PAT_PW_EVENT_ID,
                    PW_EVENT_MODULE_ID)
           values( pi_vPatientID,
                  v_recPWEventModuleSelect.MID,
                  0,
                  v_recPWEventModuleSelect.REGION_ID,
                  v_recPWEventModuleSelect.SITE_ID,
                  null,
                  null,
                  v_nPatPWID,
                  null,
                  v_recPWEventModuleSelect.MODULE_FOR,
                  v_recPWEventModuleSelect.SORT_ORDER,
                  v_dtScheduled,
                  v_nPatPWEventID,
                  v_nEventModuleID);

           commit;  
         
         end if;
         
         END LOOP;
         CLOSE v_rsPWEventModuleSelect;
         
     
      END LOOP;
      --CLOSE v_rsPWEventSelect;
    
    END LOOP;   
    
    --merge pathway events
    v_nMerged := 0;
    LOOP
    EXIT WHEN v_nMerged = 1;
    
        MergePathwayEvents(pi_vPatientID, v_nPatPWID, v_nMerged);
    
    END LOOP;
        
    --return the patient pathway id
    po_nPatPWID := v_nPatPWID;
           
    commit;

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/***
Insert pathway event
***/
procedure InsertPathwayEvent (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPWID                  in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1000) :=
       'SELECT t.*, 
              
              t2.module_for, 
              t2.sort_order,
              
              t3.module, 
              t3.description, 
              t3.module_alt_lang, 
              t3.description_alt_lang, 
              t3.acronym, 
              t3.score_logic   
              
       FROM tbicds.PAT_PW_EVENT_MODULE t,
            tbicds.CPA_PW_EVENT_MODULE t2,
            tbicds.intake_module t3 
            
       WHERE t.patient_id = :PATIENT_ID 
         
         and t2.PW_ID = t.PW_ID
         and t2.PW_EVENT_ID = t.PW_EVENT_ID 
         and t2.MID = t.MID
         
         and t3.mid = t.mid
         
       ORDER BY t.cpa_id, t.pw_id, t.pw_event_id, t2.sort_order ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/***
Insert pat pw event modules
***/
procedure InsertPatPWEventModules (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      pi_vMIDS                  in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

      v_nIndex number := 0;
      v_vPiece varchar2(4000) := '';   
      v_nMID number := 0;   
   
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
     loop
      
      --get one mid   
      v_vPiece := pck_common.GetPiece(pi_vMIDs, ',' , v_nIndex);
      EXIT WHEN v_vPiece is null;
            
      begin
        
           --get the mid and bump the index
           v_nMID := to_number(v_vPiece);
           v_nIndex := v_nIndex +1;
           
           insert into 
           pat_pw_event_module(PATIENT_ID,
                                    MID,
                                    STATUS,
                                    REGION_ID,
                                    SITE_ID,
                                    DATE_STARTED,
                                    DATE_COMPLETED,
                                    PAT_PW_ID,
                                    INTAKE_ID,
                                    MODULE_FOR,
                                    SORT_ORDER,
                                    PAT_PW_EVENT_ID,
                                    DATE_SCHEDULED)
            values(pi_vPatientID,
                   
                   v_nMID,
                   
                   0,
                   
                   (select REGION_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                   
                    (select SITE_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                    
                    null,
                    null,
                   
                   (select PAT_PW_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                   
                    null,
                    1,
                    9999999,
                    pi_nPatPWEventID,
                    sysdate);
                                    
           commit;                                 
           
      
      exception
      when others then
           null;
      end;
      
     end loop;
   
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/***
Update the pw event module list
****/
procedure UpdatePatPWEventModules (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      
      pi_vEventTitle            in varchar2,
      pi_dtEventDate            in date,
      pi_nAdjustFuture          in number,
      
      pi_vMIDS                  in varchar2,
      pi_vModuleFors            in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

      v_nIndex number := 0;
      v_vMIDPiece varchar2(4000) := ''; 
      v_vFORPiece varchar2(4000) := '';  
      v_nMID number := 0;   
      v_nModuleFor number := 2;
      
      v_dtOldScheduled date := null;
      v_nPatPWID number := 0;
      v_nDays number := 0;
      v_nEventModuleID number := 0;
   
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    v_nEventModuleID := 0;
    
    --keep the original date for calculations
    select date_scheduled, pat_pw_id 
    into v_dtOldScheduled, v_nPatPWID
    from pat_pw_event 
    where pat_pw_event_id = pi_nPatPWEventID
    and patient_id = pi_vPatientID;
    
    --update title and date
    update pat_pw_event 
    set event_title = pi_vEventTitle,
        date_scheduled = pi_dtEventDate
    where pat_pw_event_id = pi_nPatPWEventID
    and patient_id = pi_vPatientID;
    commit;
        
    --get the number of days this date is different    
    if pi_nAdjustFuture = 1 then
       
       --get the date diff
       SELECT trunc(pi_dtEventDate)- (v_dtOldScheduled) 
         into v_nDays 
         FROM DUAL;
        
       --update all events after this event
       update pat_pw_event pe
          set pe.date_scheduled =  pe.date_scheduled + v_nDays
        where patient_id = pi_vPatientID
          and pe.pat_pw_event_id > pi_nPatPWEventID
          and pe.pat_pw_id = pat_pw_id;
       commit;         
      
    end if;
    
    --remove all the current modules, will update below
    delete from pat_pw_event_module pem 
    where pem.pat_pw_event_id = pi_nPatPWEventID
    and pem.patient_id = pi_vPatientID 
    and pem.intake_id is null;
    
    --loop and add modules
     loop
      
      --get one mid   
      v_vMIDPiece := pck_common.GetPiece(pi_vMIDs, ',' , v_nIndex);
      
      --get one module for
      v_vFORPiece := pck_common.GetPiece(pi_vModuleFors, ',' , v_nIndex);
      
      EXIT WHEN v_vMIDPiece is null;
            
      begin
        
           --get the mid and bump the index
           v_nMID := to_number(v_vMIDPiece);
           v_nModuleFor := to_number(v_vFORPiece);
           v_nIndex := v_nIndex +1;
           
           select SEQPATPWEVENTMODULEID.Nextval 
           into v_nEventModuleID from dual;
           
           insert into 
           pat_pw_event_module(PATIENT_ID,
                               MID,
                               STATUS,
                               REGION_ID,
                               SITE_ID,
                               DATE_STARTED,
                               DATE_COMPLETED,
                               PAT_PW_ID,
                               INTAKE_ID,
                               MODULE_FOR,
                               SORT_ORDER,
                               PAT_PW_EVENT_ID,
                               DATE_SCHEDULED,
                               PW_EVENT_MODULE_ID)
            values(pi_vPatientID,
                   
                   v_nMID,
                   
                   0,--status
                   
                   (select REGION_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                   
                    (select SITE_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                    
                    null, --date started
                    
                    null, --date completed
                   
                   (select PAT_PW_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                   
                    null, --intake_id
                    
                    v_nModuleFor, --module for
                    
                    (select nvl(max(sort_order), 0) + 1 
                       from pat_pw_event_module 
                      where pat_pw_event_id = pi_nPatPWEventID),
                      
                    pi_nPatPWEventID,
                    
                    sysdate,
                    
                    v_nEventModuleID);
                                    
           commit;                                 
           
      
      exception
      when others then
           null;
      end;
      
     end loop;
   
    
    commit;

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*update a pathway event module*/
procedure UpdatePathwayEventModule (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPWID                  in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1000) :=
       'SELECT t.*, 
              
              t2.module_for, 
              t2.sort_order,
              
              t3.module, 
              t3.description, 
              t3.module_alt_lang, 
              t3.description_alt_lang, 
              t3.acronym, 
              t3.score_logic   
              
       FROM tbicds.PAT_PW_EVENT_MODULE t,
            tbicds.CPA_PW_EVENT_MODULE t2,
            tbicds.intake_module t3 
            
       WHERE t.patient_id = :PATIENT_ID 
         
         and t2.PW_ID = t.PW_ID
         and t2.PW_EVENT_ID = t.PW_EVENT_ID 
         and t2.MID = t.MID
         
         and t3.mid = t.mid
         
       ORDER BY t.cpa_id, t.pw_id, t.pw_event_id, t2.sort_order ASC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Updates Patient Event Module status after a module is completed
*****/
procedure UpdatePatPWEventModule (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPWID                  in number,
      pi_nPatPWEvtID            in number,
      pi_nMID                   in number,
      pi_nIntakeID              in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

     v_vSQL varchar2(1000) := '
        update PAT_PW_EVENT_MODULE t
           set t.status = 1,
               t.intake_id = :INTAKE_ID,
               t.date_started = sysdate,
               t.date_completed = sysdate,
               t.completed_by = :USER_ID
         where t.patient_id = :PATIENT_ID
           and t.pat_pw_id = :PAT_PW_ID
           and t.pat_pw_event_id = :PAT_PW_EVT_ID
           and t.mid = :MID';

begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --execute the SQL
    execute immediate v_vSQL 
    using pi_nIntakeID, 
          pi_nUserID,
          pi_vPatientID,
          pi_nPWID,
          pi_nPatPWEvtID, 
          pi_nMID;
                 
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*update a patient pathway event module*/
procedure UpdatePatPWEventModule (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPWID                  in number,
      pi_nPatPWEvtID            in number,
      pi_nMID                   in number,
      pi_nIntakeID              in number,
      pi_nPwEvtModID              in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

     v_vSQL varchar2(1000) := '
        update PAT_PW_EVENT_MODULE t
           set t.status = 1,
               t.intake_id = :INTAKE_ID,
               t.date_started = sysdate,
               t.date_completed = sysdate,
               t.completed_by = :USER_ID
         where t.patient_id = :PATIENT_ID
           and t.pat_pw_id = :PAT_PW_ID
           and t.pat_pw_event_id = :PAT_PW_EVT_ID
           and t.mid = :MID
           and t.PW_EVENT_MODULE_ID = :PW_EVENT_MODULE_ID';

begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --execute the SQL
    execute immediate v_vSQL 
    using pi_nIntakeID, 
          pi_nUserID,
          pi_vPatientID,
          pi_nPWID,
          pi_nPatPWEvtID, 
          pi_nMID,
          pi_nPwEvtModID;
                 
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


end PCK_CPA;
/

prompt
prompt Creating package body PCK_DEMOGRAPHICS
prompt ======================================
prompt
create or replace package body tbicds.PCK_DEMOGRAPHICS is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

   /*get relationship recordset*/
   procedure GetRelationshipSelfRS(
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2,
      rs                  out RetRefCursor
      )
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select * '
                || 'from tbicds.stat_relationship t '
                || 'where active = 1 '
                || 'or t.relationship_id = 9 '
                || 'order by active ';
      open rs for v_vSql;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_DEMOGRAPHICS.GetRelationshipSelfRS(): ' || sqlErrm;
   end;
   
   /*get state recordset*/
   procedure GetStateRS(
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2,
      rs                  out RetRefCursor
      )
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select * from tbicds.stat_states t where active = 1';
      open rs for v_vSql;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_DEMOGRAPHICS.GetStateRS(): ' || sqlErrm;
   end;
   
   /*get gender recordset*/
   procedure GetGenderRS(
      pi_vSessionID       in varchar2,
      pi_vSessionClientIP in varchar2,
      pi_nUserID          in number,
      po_nStatusCode      out number,
      po_vStatusComment   out varchar2,
      rs                  out RetRefCursor
      )
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select * from tbicds.stat_gender t where active = 1';
      open rs for v_vSql;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_DEMOGRAPHICS.GetGenderRS(): ';
   end;
   
   /*get gender description by id recordset*/
   procedure GetGenderDescByIdRS (
      pi_vSessionID              in varchar2,
      pi_vSessionClientIP        in varchar2,
      pi_nUserID                 in number,
      pi_vGenderID               in varchar2,
      po_nStatusCode             out number,
      po_vStatusComment          out varchar2,
      rs                         out RetRefCursor
     )
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode := 0;--0 = success
      po_vStatusComment := '';
   
      --open recordset
      v_vSql := 'select * from tbicds.stat_gender t where t.gender_id = :P0 and t.active = 1';
      open rs for v_vSql using pi_vGenderID;
   
   exception
      when others
      then
         po_nStatusCode := 1;
         po_vStatusComment := 'PCK_DEMOGRAPHICS.GetGenderDescByIdRS(): ';
   end;

end;
/

prompt
prompt Creating package body PCK_ENCOUNTER_INTAKE
prompt ==========================================
prompt
create or replace package body tbicds.PCK_ENCOUNTER_INTAKE is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

   /*get all the flags for an encounter*/
   procedure GetEncounterFlags(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vEncounterID     in varchar2,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out Pck_Utl_Common.refCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      -- default status to ok
      po_nStatusCode    := Pck_Utl_Common.c_nResultStatus_Success;
      po_vStatusComment := null;
      
      v_vSql := 'select t.*, it.topic, it.alternate_language as topic_alt, it.topic_image '
                || 'from tbicds.encounter_intake_flag t, tbicds.intake_topic it '
                || 'where t.encounter_id = :P0 '
                || 'and t.mid = it.mid '
                || 'and t.tid = it.tid '
                || 'order by t.mid, t.tid, t.flag_id';
      open rs for v_vSql using pi_vEncounterID;
  
   exception
      when others then
         po_nStatusCode    := Pck_Utl_Common.c_nResultStatus_Error;
         po_vStatusComment := 'PCK_ENCOUNTER_INTAKE.GetEncounterFlags(): ';
   end;

  /*
   get all the flags for an encounter intake
  */
   procedure GetEncounterIntakeFlags(pi_vSessionID         in varchar2,
                                    pi_vSessionClientIP   in varchar2,
                                    pi_nUserID            in number,
                                    pi_vEncounterID       in varchar2,
                                    pi_vEncounterIntakeID in number,
                                    po_nStatusCode        out number,
                                    po_vStatusComment     out varchar2,
                                    rs                    out Pck_Utl_Common.refCursor)
   is
      v_vSql                               varchar2(4000);
    v_lSQL long := '';
   begin
      -- default status to ok
      po_nStatusCode    := Pck_Utl_Common.c_nResultStatus_Success;
      po_vStatusComment := null;
      
      v_vSql := 'select t.*, it.topic, it.alternate_language as topic_alt, it.topic_image '
                || 'from tbicds.encounter_intake_flag t, tbicds.intake_topic it '
                || 'where t.encounter_id = :P0 '
                || 'and t.encounter_intake_id = :P1 '
                || 'and t.mid = it.mid '
                || 'and t.tid = it.tid '
                || 'order by t.mid, t.tid, t.flag_id';
      open rs for v_vSql using pi_vEncounterID, pi_vEncounterIntakeID;
  
   exception
      when others then
         po_nStatusCode    := Pck_Utl_Common.c_nResultStatus_Error;
         po_vStatusComment := 'PCK_ENCOUNTER_INTAKE.GetEncounterIntakeFlags(): ';
   end;

   /*
   Get the latest un-complete encounter for this module
   */
   procedure getIntakePatientID(pi_vSessionID         in varchar2,
                               pi_vSessionClientIP   in varchar2,
                               pi_nUserID            in number,
                               pi_vEncounterID       in varchar2,
                               pi_nEncounterIntakeID in number,
                               po_vPatientID         out varchar2,
                               po_nStatusCode        out number,
                               po_vStatusComment     out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_vPatientID     := '';
      po_nStatusCode    := 0;
      po_vStatusComment := '';
      
      --get the latest un-complete encounter for this module
      begin
         --get the patient id from the
         --portal user id passed in
         v_vSql := 'select t.patient_id from tbicds.encounter t where t.encounter_id = :P0';
         execute immediate v_vSql into po_vPatientID using pi_vEncounterID;
      
      exception
         when others then
            po_vPatientID := '';
      end;
  
   exception
      when others then
         po_nStatusCode    := Pck_Utl_Common.c_nResultStatus_Error;
         po_vStatusComment := 'getIntakeAltLang(): ';
   end;

   /*
   Get alt language for the encounter
   */
   procedure getIntakeAltLang(pi_vSessionID         in varchar2,
                             pi_vSessionClientIP   in varchar2,
                             pi_nUserID            in number,
                             pi_vEncounterID       in varchar2,
                             pi_nEncounterIntakeID in number,
                             po_nOutAltLang        out number,
                             po_nStatusCode        out number,
                             po_vStatusComment     out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nOutAltLang    := 0;
      po_nStatusCode    := 0;
      po_vStatusComment := '';
      
      --get the latest un-complete encounter for this module
      begin
         --get the patient id from the
         --portal user id passed in
         v_vSql := 'select alternate_language from tbicds.encounter_intake where encounter_id = :P0 and encounter_intake_id = :P1';
         execute immediate v_vSql into po_nOutAltLang using pi_vEncounterID, pi_nEncounterIntakeID; 
      
      exception
         when others then
            po_nOutAltLang := 0;
      end;

   exception
      when others then
         po_nStatusCode    := Pck_Utl_Common.c_nResultStatus_Error;
         po_vStatusComment := 'getIntakeAltLang(): ';
   end;

   /*
   Tries to retrieve the encounter ID for the passed MID.
    If there is no encounter, it inserts a new encounter
    of type 7 (portal visit)
   */
   procedure GetEncounterIDFromModule(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     pi_nModuleID        in number,
                                     pi_vPatientID       in varchar2,
                                     pi_nTreatmentID     in number,
                                     po_vEncounterID     out varchar2,
                                     po_nStatusCode      out number,
                                     po_vStatusComment   out varchar2)
   is
      v_vSql                               varchar2(4000);
      v_nSeq number;
      v_nCnt number;
      null_data EXCEPTION;
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
   
      --get the encounter id for the latest
      --encounter intake matching the
      --mid passed in and that is not completed
      --this is so we can continue an assessment
      v_vSql := 'select max(t.encounter_id) '
                || 'from tbicds.encounter_intake t, tbicds.encounter e '
                || 'where t.encounter_id = e.encounter_id '
                || 'and e.patient_id = :P0 '
                || 'and t.mid = :P1 '
                || 'and nvl(complete, 0) < 1';
      execute immediate v_vSql into po_vEncounterID using pi_vPatientID, pi_nModuleID;
      
      --raise an exception
      if po_vEncounterID is null then
         RAISE null_data;
      end if;
      
   --if any of the above fail then we need to create a new:
   --   1. encounter (encounter type 99 = portal)
   --   2. encounter intake
   --get latest treatment id 
   exception
      when others then
         begin
           --encounter id if none, insert new encounter
         
           --get latest open encounter id, if not signed
           --then use it to create the encounter intake
           --just get the encounter for today if it exists
           v_vSql := 'select max(e.encounter_id) '
                     || 'from tbicds.encounter e '
                     || 'where e.patient_id = :P0 '
                     || 'and e.provider_signature_id is null ';
           execute immediate v_vSql into po_vEncounterID using pi_vPatientID;
         
         exception
            when others then
               po_vEncounterID := null;
         end; --encounter id if none, insert new encounter
 
         if (po_vEncounterID is null) then
            begin
               --does not have an open encounter for today
               --so create a new one based on the patient_id and
               --a sequence
               v_vSql := 'select tbicds.SEQ_ENCOUNTERID.nextval from dual';
               execute immediate v_vSql into v_nSeq;
               
               --new encounter id
               po_vEncounterID := mid(pi_vPatientID, 0, length(pi_vPatientID) - length(to_char(v_nSeq)))
                                  || to_char(v_nSeq);
               
               --insert a new encounter
               v_vSql := 'insert into tbicds.encounter '
                         || '(encounter_id, encounter_date, treatment_id, patient_id, encounter_type_id) '
                         || 'values (:P0, :P1, :P2, :P3, :P4)';
               execute immediate v_vSql using po_vEncounterID, sysdate, pi_nTreatmentID, pi_vPatientID, 99;
               commit;
           
            exception
               when others then
                  po_nStatusCode    := 1;
                  po_vStatusComment := 'PCK_ENCOUNTER_INTAKE.GetEncounterIDFromForModule(): ';
            end;
         end if; --if (v_strEncounterID is null) then
   end;

   /*
   get the the encounter_intake_id.  It checks for the existance
    of a record by checking the COMPLETE field.  If null, then
    there is no record.  In this case it inserts a new record. if
    complete exist and 0 then it returns the current id. 
   
    NOTE: It should never be called for a completed module 
   */
   procedure NewEncounterIntake(pi_vSessionID         in varchar2,
                               pi_vSessionClientIP   in varchar2,
                               pi_nUserID            in number,
                               pi_nModuleID          in number,
                               pi_vEncounterID       in varchar2,
                               pi_nAltLang           in number,
                               po_nEncounterIntakeID out number,
                               po_nStatusCode        out number,
                               po_vStatusComment     out varchar2)
   is
      v_nIncompleteCount number := 0;
      v_nIntakeCount     number := 0;
      v_nEiid            number := 0;
  
      v_vIncompleteCountSql constant varchar(32767) := 'select count(t.encounter_intake_id)
          from tbicds.encounter_intake t
          where t.encounter_id = :EncounterId
          and t.mid = :Mid
          and t.complete = 0';
      
      v_vIntakeCountSql constant varchar(32767) := 'select count(t.encounter_intake_id)
          from tbicds.encounter_intake t
          where t.encounter_id = :EncounterId';
      
      v_vMaxIdSql constant varchar(32767) := 'select max(t.encounter_intake_id)
         from tbicds.encounter_intake t
         where t.encounter_id = :EncounterId';
      
      v_vInsertSql constant varchar(32767) := 'insert into tbicds.encounter_intake t
          (t.encounter_id,
          t.encounter_intake_id,
          t.mid,
          t.intake_type,
          t.score,
          t.read_only,
          t.complete,
          t.alternate_language,
          t.review_encounter_id)
          values
          (:EncounterId,
          :EncounterIntakeId,
          :Mid,
          :IntakeType,
          :Score,
          :ReadOnly,
          :Complete,
          :AlternateLanguage,
          :ReviewEncounterId)';
      
      v_vIncompleteIdSql constant varchar(32767) := 'select t.encounter_intake_id
          from tbicds.encounter_intake t
          where t.encounter_id = :EncounterId
          and t.mid = :Mid
          and t.complete = 0';
   begin
      execute immediate v_vIncompleteCountSql into v_nIncompleteCount using pi_vEncounterID, pi_nModuleID;
  
      if v_nIncompleteCount = 0 then
         execute immediate v_vIntakeCountSql into v_nIntakeCount using pi_vEncounterID;
      
         if v_nIntakeCount = 0 then
            v_nEiid := 1;
         else
            execute immediate v_vMaxIdSql into v_nEiid using pi_vEncounterID;
            v_nEiid := v_nEiid + 1;
         end if;
         
         execute immediate v_vInsertSql using pi_vEncounterID, v_nEiid, pi_nModuleID, 1, 0, 0, 0, pi_nAltLang, '';
         
         po_nEncounterIntakeID := v_nEiid;
      else
         execute immediate v_vIncompleteIdSql into po_nEncounterIntakeID using pi_vEncounterID, pi_nModuleID;
      end if;
  
   exception
      when others then
         po_nEncounterIntakeID := -1;
         po_nStatusCode        := 1;
         po_vStatusComment     := 'PCK_ENCOUNTER_INTAKE.NewEncounterIntakeRS(): ';
   end;

   /*
   get a piece of a string given a delimeter and a position
   */
   function GetPiece(strData      in varchar2,
                    strDelimiter in varchar2,
                    nPosition    in NUMBER) return varchar2
   is
      strWorking varchar2(4000);
      strPiece   varchar2(400);
      pos        number;
      nPos2      number;
      nCount     number;
   begin
      --the piece to return
      strPiece := '';
      
      --set working to data
      strWorking := strData;
      
      --put a delimeter on the front for parsing if needed
      if substr(strWorking, 1, 1) != strDelimiter then
         strWorking := strDelimiter || strWorking;
      end if;

      --find the piece between the ~'s ie... "~piece~"
      pos    := -1;
      nCount := -1;
      
      while (pos != 0) loop
         pos := instr(strWorking, strDelimiter);
         
         if pos != 0 then
            --increment count
            nCount := nCount + 1;
            
            --found the piece...
            if nCount = nPosition then
               if (pos + 1 > length(strWorking) - 1) then
                  --nothing
                  strPiece := '';
               else
                  strWorking := substr(strWorking, pos + 1);
                  nPos2      := instr(strWorking, strDelimiter);
                  
                  if nPos2 = 0 then
                     --last piece
                     strPiece := strWorking;
                     return ltrim(rtrim(strPiece));
                  else
                     strPiece := substr(strWorking, 0, nPos2 - 1);
                     return ltrim(rtrim(strPiece));
                  end if;
               end if;
            else
               strWorking := substr(strWorking, pos + 1);
            end if;
         end if;
      end loop;
      
      return ltrim(rtrim(strPiece));
  
   exception
      when others then
         return '';
   end;

   /*
   get all Encounter Intake Responses count recordset
   */
   procedure GetResponsesCountRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vEncounterID     in varchar2,
                                pi_vMIDs            in varchar2,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select count(*) as count_resp, t.mid '
                || 'from tbicds.encounter_intake_responses t '
                || 'where t.encounter_id = :P0 '
                || 'and instr(:P1, '',''||t.mid||'','') > 0 '
                || 'group by t.mid '
                || 'order by t.mid ';
      open rs for v_vSql using pi_vEncounterID, ','||pi_vMIDs||',';
  
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_INTAKE.GetResponsesCountRS(): ';
   end;

   ------------------------------------------------------------------
   -- This SP will return a recordset with the data fields necessary
   -- to fill the education encounter list
   ------------------------------------------------------------------
   procedure GetIntakesForEducationRS(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     pi_vPatientID       in varchar2,
                                     po_nStatusCode      out number,
                                     po_vStatusComment   out varchar2,
                                     rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select m.mid, m.module as mid, e.encounter_date as edate '
                || 'from tbicds.intake_module m, tbicds.encounter e, tbicds.encounter_intake ei '
                || 'where e.patient_id = :P0 '
                || 'and ei.encounter_id = e.encounter_id '
                || 'and m.mid = ei.mid '
                || 'order by e.encounter_date ';
      open rs for v_vSql using pi_vPatientID;
  
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_INTAKE.GetIntakesForEducationRS(): ';
   end;
   
   /*get intakes for review recordset*/
   procedure GetIntakesForReviewRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  pi_vPatientID       in varchar2,
                                  pi_vEncounterID      in varchar2,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
      v_vPatientID  varchar2(50);
      v_nModalityID number;
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vPatientID  := pi_vPatientID;
      
      --get modality id from encounter
      begin
         v_vSql := 'select e.encounter_type_id '
                   || 'from tbicds.encounter e '
                   || 'where e.encounter_id = :P0 '
                   || 'and e.patient_id = :P1 ';
         execute immediate v_vSql into v_nModalityID using pi_vEncounterID, v_vPatientID;
      exception
         when others then
            v_nModalityID := -1;
      end;
  
      v_vSql := 'select * from ('
                || 'select img.module_group_descr, m.module, p.*, imgm.sort_order '
                || 'from tbicds.patient_module p, '
                || 'tbicds.intake_module m, '
                || 'tbicds.intake_module_group img, '
                || 'tbicds.intake_module_group_mid imgm '
                || 'where m.mid = p.mid '
                || 'and img.module_group_id = p.module_group_id '
                || 'and imgm.module_group_id = p.module_group_id '
                || 'and imgm.mid = p.mid '
                || 'and p.patient_id = :P0 '
                --and p.status = 1
                || 'and p.module_group_id in (select module_group_id from tbicds.intake_module_group where stat_modality_id = :P1) '
                || ') t1 '
                || 'left join ('
                || 'select e.patient_id, i.* '
                || 'from tbicds.encounter e, tbicds.encounter_intake i '
                || 'where e.encounter_id = i.encounter_id '
                || 'and i.intake_group_id in (select module_group_id from tbicds.intake_module_group where stat_modality_id = :P2) '
                || 'and e.patient_id = :P3 '
                || ') t2 '
                || 'on t2.patient_id = t1.patient_id '
                || 'and t2.mid = t1.mid '
                || 'and t2.intake_group_id = t1.module_group_id '
                || 'order by t1.MODULE_GROUP_ID, t1.sort_order, t1.status desc, t1.date_completed ';
      open rs for v_vSql using v_vPatientID, v_nModalityID, v_nModalityID, v_vPatientID;
  
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_INTAKE.GetIntakesForReviewRS(): ';
   end;

end;
/

prompt
prompt Creating package body PCK_FX_SEC
prompt ================================
prompt
create or replace package body tbicds.PCK_FX_SEC is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*audits a transaction to the syslog*/
  procedure SysLogAuditTransaction(pi_vSessionID in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_nStatus          in number,
                                   pi_vAuditXML        in varchar2,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2)
  
  is
  
  begin
    
    --6 = normal operational messages
    --3 = error conditions
  
    --default status to good
    po_nStatusCode    := 0; --0 = success, other than zero = failed
    po_vStatusComment := '';
  
  
    --commented out on drdb_dev since we are using windows DB
   -- if pi_nStatus != 0 then
   --    sys.writesyslog(3, pi_vAuditXML);
   -- else
    --   sys.writesyslog(6, pi_vAuditXML);
   -- end if;
    
   -- po_nStatusCode    := 1;
   -- po_vStatusComment := '167 - An error occurred while auditing a transaction, Please contact your system administrator.';
    
    return;
       
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '167 - An error occurred while auditing a transaction, Please contact your system administrator.';
  end;

  /*
  creates a database session for a user. used after a successful login to an external
  system such as MDWS to establish a session for the user in the database
  */
  procedure CreateSession(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vWebSessionID    in varchar2,
                          po_vDBSessionID     out varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2) 
   is
    v_vSql         varchar2(4000);
    v_vDBSessionID varchar2(4000) := '';
    v_vStat  varchar2(4000) := '';
    v_nStat number := 0;
  begin
    --get a new db session id:
    v_vDBSessionID := '';
    v_vSql         := 'select t.SID || :P0 || t.SERIAL# || t.USER# || :P1 || :P2 ' ||
                      'from sys.v_$session t ' || 'where t.audsid = :P3 ';
    execute immediate v_vSql
      into v_vDBSessionID
      using DBMS_CRYPTO.RandomBytes(3), DBMS_CRYPTO.RandomBytes(3), userenv('sessionid'), userenv('sessionid');
  
    --clean up any old sessions, users can only login once.
    v_vSql := 'delete from tbicds.fx_session where fx_user_id = :P0';
    execute immediate v_vSql
      using pi_nUserID;
    commit;
  
    v_vSql := 'delete from tbicds.fx_session where db_session_id = :P0';
    execute immediate v_vSql
      using v_vDBSessionID;
    commit;
  
    v_vSql := 'delete from tbicds.fx_session_value where db_session_id = :P0';
    execute immediate v_vSql
      using v_vDBSessionID;
    commit;
  
    --insert a record into fx_session
    v_vSql := 'insert into tbicds.fx_session (' ||
              'fx_user_id, web_session_id, db_session_id, date_created, date_last_action, expired, client_ip) ' ||
              'values (' || ':P0, :P1, :P2, :P3, :P4, :P5, :P6) ';
    execute immediate v_vSql
      using pi_nUserID, pi_vWebSessionID, v_vDBSessionID, sysdate, sysdate, 0, pi_vSessionClientIP;
  
    --add an audit record for the success
    --v_vSql := 'insert into tbicds.fx_audit (' ||
    --          'db_session_id, client_ip, fx_user_id, audit_date, audit_name, audit_data) ' ||
    --          'values (' || ':P0, :P1, :P2, :P3, :P4, :P5) ';
    --execute immediate v_vSql
    --  using v_vDBSessionID, pi_vSessionClientIP, pi_nUserID, sysdate, 'LOGIN', 'SUCCESS';
    --commit;
    begin
      
      SysLogAuditTransaction(v_vDBSessionID,
                             pi_vSessionClientIP,
                             pi_nUserID,
                             0,
                             'SESSION_CREATED' 
                             || '|' || pi_vSessionClientIP
                             || '|' || pi_nUserID
                             || '|' || 'SUCCESS',
                             v_nStat,
                             v_vStat);
   
    exception
    when others then
      null;
    end;
    
  
    --keep the session id
    po_vDBSessionID := v_vDBSessionID;
  
  exception
    when others then
      rollback;
      po_vDBSessionID   := '';
      po_nStatusCode    := pck_common.c_nStatus_Error;
      po_vStatusComment := '';
  end;

  /*validate the password against rules*/
  procedure ValidatePassword(pi_vKey           in varchar2,
                             pi_nUserID        in number,
                             pi_vUserName      in varchar2,
                             pi_vOldPassword   in varchar2,
                             pi_vPassword      in varchar2,
                             pi_vCOldPassword  in varchar2,
                             pi_vCPassword     in varchar2,
                             pi_vCUserName     in varchar2,
                             pi_nResetPassword in number,
                             po_nStatusCode    out number,
                             po_vStatusComment out varchar2) 
   is
  
    v_nFXUserID            number := 0;
    v_nUserCount           number := 0;
    v_dDatePasswordChanged date;
    v_vPREV_PWD1           varchar2(2000);
    v_vPREV_PWD2           varchar2(2000);
    v_vPREV_PWD3           varchar2(2000);
    v_vPREV_PWD4           varchar2(2000);
    v_vPREV_PWD5           varchar2(2000);
    v_vPREV_PWD6           varchar2(2000);
    v_vPREV_PWD7           varchar2(2000);
    v_vPREV_PWD8           varchar2(2000);
    v_vPREV_PWD9           varchar2(2000);
    v_vPREV_PWD10          varchar2(2000);
  
    --suat user personal information
    v_vUsrPDataName  varchar2(2000);
    v_vUsrPDataName1 varchar2(2000);
    v_vUsrPDataName2 varchar2(2000);
  
    v_vUsrPDataTitle    varchar2(2000);
    v_vUsrPDataUnit     varchar2(2000);
    v_vUsrPDataSquadron varchar2(2000);
    v_vUsrPDataPhone    varchar2(2000);
  
    --patient personal information
    v_vPatPDataFirstName  varchar2(2000);
    v_vPatPDataLastName   varchar2(2000);
    v_vPatPDataSSN        varchar2(2000);
    v_vPatPDataCity       varchar2(2000);
    v_vPatPDataPostalCode varchar2(2000);
    v_vPatPDataHomePhone  varchar2(2000);
    v_vPatPDataWorkPhone  varchar2(2000);
    v_dtPatPDataDOB       date;
    v_vPWDCheck           varchar2(4000);
  
    v_vCUserName1 varchar2(2000);
    v_vCUsername2 varchar2(2000);
    v_vUNCheck    varchar2(2000);
    v_nResetPWD   number;
  
    v_nPWDDiffCharacterCount number := 0;
    v_nPWDGreatest           number := 0;
    v_nPWDLeast              number := 0;
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --get data needed for the check
    select date_password_changed,
           PREV_PWD1,
           PREV_PWD2,
           PREV_PWD3,
           PREV_PWD4,
           PREV_PWD5,
           PREV_PWD6,
           PREV_PWD7,
           PREV_PWD8,
           PREV_PWD9,
           PREV_PWD10,
           nvl(t.reset_password, 0)
      into v_dDatePasswordChanged,
           v_vPREV_PWD1,
           v_vPREV_PWD2,
           v_vPREV_PWD3,
           v_vPREV_PWD4,
           v_vPREV_PWD5,
           v_vPREV_PWD6,
           v_vPREV_PWD7,
           v_vPREV_PWD8,
           v_vPREV_PWD9,
           v_vPREV_PWD10,
           v_nResetPWD
      from tbicds.fx_user t
     where t.fx_user_id = pi_nUserID;
  
    --limit user changes to their account passwords 
    --once every 24 hours with the exception of privileged 
    --or administrative users. or in the case where the 
    --pwd was reset this keeps the user from spinning through pwds to get to
    --an old pwd for convenience
    if nvl(pi_nResetPassword, 0) < 1 then
      if (v_dDatePasswordChanged is not null) and
         (sysdate - 1 < v_dDatePasswordChanged) and
         not HASUSERRIGHT(v_nFXUserID, PCK_COMMON.c_nAdministratorUR) then
        po_nStatusCode    := 1;
        po_vStatusComment := 'Password cannot be changed in less than 24 hours since last change!';
        return;
      end if;
    end if;
  
    --make sure the password is not the same as the 10 past passwords
    if pi_nUserID > 0 then
    
      if pi_vPassword = v_vPREV_PWD1 or pi_vPassword = v_vPREV_PWD2 or
         pi_vPassword = v_vPREV_PWD3 or pi_vPassword = v_vPREV_PWD4 or
         pi_vPassword = v_vPREV_PWD5 or pi_vPassword = v_vPREV_PWD6 or
         pi_vPassword = v_vPREV_PWD7 or pi_vPassword = v_vPREV_PWD8 or
         pi_vPassword = v_vPREV_PWD9 or pi_vPassword = v_vPREV_PWD10 or
         pi_vPassword = pi_vOldPassword then
      
        po_nStatusCode    := 1;
        po_vStatusComment := 'New password cannot be the same as recent past password. Please choose a different password!';
        return;
      end if;
    
    end if;
  
    --ensure passwords do not contain personal information such as names, telephone numbers, account names, birthdates, or dictionary words. 
    for rec in (select t.restricted_name from fx_restricted_name t) loop
      if (instr(upper(pi_vCPassword), upper(rec.restricted_name)) > 0) then
        po_nStatusCode    := 1;
        po_vStatusComment := 'Password cannot contain personal information such as names, telephone numbers, account names, birthdates, or dictionary words!';
        return;
      end if;
    end loop;
  
    --new account passwords differ from the previous password by at least four characters when a password is changed. 
    select greatest(length(pi_vCOldPassword), length(pi_vCPassword)),
           least(length(pi_vCOldPassword), length(pi_vCPassword))
      into v_nPWDGreatest, v_nPWDLeast
      from dual;
    v_nPWDDiffCharacterCount := v_nPWDGreatest - v_nPWDLeast;
    if v_nPWDDiffCharacterCount < 4 then
      for i in 1 .. v_nPWDLeast loop
        if (substr(pi_vCOldPassword, i, 1) <> substr(pi_vCPassword, i, 1)) then
          v_nPWDDiffCharacterCount := v_nPWDDiffCharacterCount + 1;
        end if;
        -- exit stop_loop when v_nPWDDiffCharacterCount > 3;
      end loop; -- stop_loop;
      if v_nPWDDiffCharacterCount < 4 then
        po_nStatusCode    := 1;
        po_vStatusComment := 'Passwords must be different from the previous password by at least four characters!';
        return;
      end if;
    end if;
    --for i in 1..(length(pi_vCPassword) - 4)
    --loop
    --   if (instr(pi_vCOldPassword, substr(pi_vCPassword, i, 4)) > 0)
    --  then
    --      po_nStatusCode := 1;
    --      po_vStatusComment := 'Passwords must be different from the previous password by at least four characters!';
    --      return;
    --   end if;
    --end loop;
  
    v_vPWDCheck   := upper(pi_vCPassword);
    v_vUNCheck    := upper(pi_vCUserName);
    v_vCUserName1 := pck_common.GetPiece(v_vUNCheck, '.', 0);
    v_vCUserName2 := pck_common.GetPiece(v_vUNCheck, '.', 1);
    if instr(v_vPWDCheck, pi_vCUserName) > 0 or
       instr(v_vPWDCheck, v_vCUserName1) > 0 or
       instr(v_vPWDCheck, v_vCUserName2) > 0 then
    
      po_nStatusCode    := 1;
      po_vStatusComment := 'Password cannot contain elements of your user name!';
      return;
    end if;
  
    --make sure the password does not contain personal information
    --suat user personal information
    begin
      select name, Title, Unit, Squadron, Phone
        into v_vUsrPDataName,
             v_vUsrPDataTitle,
             v_vUsrPDataUnit,
             v_vUsrPDataSquadron,
             v_vUsrPDataPhone
        from tbicds.app_user
       where fx_user_id = v_nFXUserID;
    
      v_vUsrPDataName     := upper(v_vUsrPDataName);
      v_vUsrPDataTitle    := upper(v_vUsrPDataTitle);
      v_vUsrPDataUnit     := upper(v_vUsrPDataUnit);
      v_vUsrPDataSquadron := upper(v_vUsrPDataSquadron);
      v_vUsrPDataPhone    := upper(v_vUsrPDataPhone);
    
      v_vUsrPDataName1 := pck_common.GetPiece(v_vUsrPDataName, ' ', 0);
      v_vUsrPDataName2 := pck_common.GetPiece(v_vUsrPDataName, ' ', 1);
    
      if instr(v_vPWDCheck, v_vUsrPDataName) > 0 or
         instr(v_vPWDCheck, v_vUsrPDataName1) > 0 or
         instr(v_vPWDCheck, v_vUsrPDataName2) > 0 or
         instr(v_vPWDCheck, v_vUsrPDataTitle) > 0 or
         instr(v_vPWDCheck, v_vUsrPDataUnit) > 0 or
         instr(v_vPWDCheck, v_vUsrPDataSquadron) > 0 or
         instr(v_vPWDCheck, v_vUsrPDataPhone) > 0 or
         instr(v_vPWDCheck, replace(v_vUsrPDataPhone, '-', '')) > 0 then
      
        po_nStatusCode    := 1;
        po_vStatusComment := 'Password cannot contain personal information such as names, telephone numbers, account names, birthdates, or dictionary words!';
        return;
      
      end if;
    
    exception
      when others then
        null;
    end;
  
    --patient personal information
    begin
    
      select tbicds.fnc_utl_decstr(t.FIRST_NAME, pi_vKey, t.PATIENT_ID) as first_name,
             tbicds.fnc_utl_decstr(t.LAST_NAME, pi_vKey, t.PATIENT_ID) as last_name,
             tbicds.fnc_utl_decstr(t.SSN, pi_vKey, t.PATIENT_ID) as ssn,
             t.City,
             t.Postal_Code,
             t.HomePhone,
             t.WorkPhone,
             to_date(tbicds.fnc_utl_decstr(t.dob, pi_vKey, t.PATIENT_ID),
                     'MM/DD/YYYY') as dob
        into v_vPatPDataFirstName,
             v_vPatPDataLastName,
             v_vPatPDataSSN,
             v_vPatPDataCity,
             v_vPatPDataPostalCode,
             v_vPatPDataHomePhone,
             v_vPatPDataWorkPhone,
             v_dtPatPDataDOB
        from tbicds.patient_demographics t
       where t.fx_user_id = v_nFXUserID;
    
      if instr(v_vPWDCheck, v_vPatPDataFirstName) > 0 or
         instr(v_vPWDCheck, v_vPatPDataLastName) > 0 or
         instr(v_vPWDCheck, v_vPatPDataSSN) > 0 or
         instr(v_vPWDCheck, replace(v_vPatPDataSSN, '-', '')) > 0 or
        
         instr(v_vPWDCheck, v_vPatPDataCity) > 0 or
         instr(v_vPWDCheck, v_vPatPDataPostalCode) > 0 or
         instr(v_vPWDCheck, v_vPatPDataHomePhone) > 0 or
         instr(v_vPWDCheck, replace(v_vPatPDataHomePhone, '-', '')) > 0 or
        
         instr(v_vPWDCheck, v_vPatPDataWorkPhone) > 0 or
         instr(pi_vCPassword, to_char(v_dtPatPDataDOB, 'mmddyyyy')) > 0 or
         instr(pi_vCPassword, to_char(v_dtPatPDataDOB, 'ddmmyyyy')) > 0 or
         instr(pi_vCPassword, to_char(v_dtPatPDataDOB, 'mmddyy')) > 0 or
         instr(pi_vCPassword, to_char(v_dtPatPDataDOB, 'ddmmyy')) > 0 
         
         then
      
        po_nStatusCode    := 1;
        po_vStatusComment := 'Password cannot contain personal information such as names, telephone numbers, account names, birthdates, or dictionary words!';
        return;
      
      end if;
    exception
      when others then
        null;
    end;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '5. Invalid User Name/Password';
      return;
  end;

  /*delete all session values*/
  procedure DeleteAllSessionValues(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2)
   is
  
    v_nCount number;
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nCount := 0;
  
    delete from tbicds.fx_session where db_session_id = pi_vSessionID;
    commit;
    delete from tbicds.fx_session_value
     where db_session_id = pi_vSessionID;
    commit;
    --delete from tbicds.patient_lock where session_id = pi_vSessionID;
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '158 - An error occurred while removing session values, Please contact your system administrator.';
  end;

  /*delete 1 session value*/
  procedure DeleteSessionValue(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vKey             in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2) 
 is
  
    v_nCount number;
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nCount := 0;
  
    --check that there is a session matching this session id and client ip
    select count(*)
      into v_nCount
      from tbicds.fx_session
     where db_session_id = pi_vSessionID
       and client_ip = pi_vSessionClientIP;
  
    --scrap it all, someone has a mismatched ip/sessid combo
    --this will affewctivly log the user out
    if v_nCount < 1 then
    
      delete from tbicds.fx_session where db_session_id = pi_vSessionID;
      commit;
      delete from tbicds.fx_session_value
       where db_session_id = pi_vSessionID;
      commit;
    
      po_nStatusCode    := 1;
      po_vStatusComment := 'GetSessionValue: failed!';
      return;
    
    end if;
  
    delete from tbicds.fx_session_value
     where db_session_id = pi_vSessionID
       and client_ip = pi_vSessionClientIP
       and upper(db_session_key) = upper(pi_vKey);
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '159 - An error occurred while removing a session value, Please contact your system administrator.';
  end;

  /*get a session value*/
  procedure GetSessionValue(pi_vDBSessionID     in varchar2,
                            pi_vWebSessionID    in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vKey             in varchar2,
                            po_vKeyValue        out varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2) 
  is
  
    v_nCount number;
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
    po_vKeyValue      := '';
  
    v_nCount := 0;
  
    --check that there is a session matching this session id and client ip
    select count(*)
      into v_nCount
      from tbicds.fx_session
     where db_session_id = pi_vDBSessionID
       and web_session_id = pi_vWebSessionID
       and client_ip = pi_vSessionClientIP;
  
    --scrap it all, someone has a mismatched ip/sessid combo
    --this will happen if the user times out for example
    --this will affewctivly log the user out
    if v_nCount < 1 then
    
      delete from tbicds.fx_session where db_session_id = pi_vDBSessionID;
      commit;
    
      delete from tbicds.fx_session_value
       where db_session_id = pi_vDBSessionID;
      commit;
    
      po_nStatusCode    := 1;
      po_vStatusComment := 'GetSessionValue failed, user may have timed out!';
      return;
    
    end if;
  
    select nvl(db_session_value, '')
      into po_vKeyValue
      from tbicds.fx_session_value
     where db_session_id = pi_vDBSessionID
       and client_ip = pi_vSessionClientIP
       and upper(db_session_key) = upper(pi_vKey);
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '160 - An error occurred while retrieving a session value, Please contact your system administrator.';
  end;

  /*set a session value*/
  procedure SetSessionValue(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vKey             in varchar2,
                            pi_vKeyValue        in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2) 
  is
  
    v_nCount number;
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nCount := 0;
  
    --clear any old values
    delete from tbicds.fx_session_value
     where db_session_id = pi_vSessionID
       and db_session_key = pi_vKey;
    commit;
  
    --check that there is a session matching this session iod and client ip
    select count(*)
      into v_nCount
      from tbicds.fx_session
     where db_session_id = pi_vSessionID
       and client_ip = pi_vSessionClientIP;
  
    --scrap it all, someone has a mismatched ip/sessid combo
    --this will affewctivly log the user out
    if v_nCount < 1 then
    
      delete from tbicds.fx_session where db_session_id = pi_vSessionID;
      commit;
      delete from tbicds.fx_session_value
       where db_session_id = pi_vSessionID;
      commit;
    
      po_nStatusCode    := 1;
      po_vStatusComment := 'SetSessionValue: failed!';
      return;
    
    end if;
  
    --insert a record into fx_session_value
    insert into tbicds.fx_session_value
      (db_session_id, db_session_key, db_session_value, client_ip)
    values
      (pi_vSessionID, pi_vKey, pi_vKeyValue, pi_vSessionClientIP);
  
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '161 - An error occurred while setting a session value , Please contact your system administrator.';
  end;

  
  /*change password, this will also logg the user in*/
  procedure ChangePassword(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number, --not used but passed in to maintain consistant default param list
                           pi_vKey             in varchar2,
                           pi_vUserName        in varchar2,
                           pi_vOldPassword     in varchar2,
                           pi_vPassword        in varchar2,
                           pi_vCert            in varchar2,
                           pi_vCOldPassword    in varchar2,
                           pi_vCPassword       in varchar2,
                           pi_vCUserName       in varchar2,
                           po_nUserID          out number,
                           po_vDBSessionID     out varchar2,
                           po_nTimeout         out number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2)
  
   is
  
    v_nFXUserID            number := 0;
    v_nUserCount           number := 0;
    v_dDatePasswordChanged date;
    v_vPREV_PWD1           varchar2(2000);
    v_vPREV_PWD2           varchar2(2000);
    v_vPREV_PWD3           varchar2(2000);
    v_vPREV_PWD4           varchar2(2000);
    v_vPREV_PWD5           varchar2(2000);
    v_vPREV_PWD6           varchar2(2000);
    v_vPREV_PWD7           varchar2(2000);
    v_vPREV_PWD8           varchar2(2000);
    v_vPREV_PWD9           varchar2(2000);
    v_vPREV_PWD10          varchar2(2000);
  
    --suat user personal information
    v_vUsrPDataName  varchar2(2000);
    v_vUsrPDataName1 varchar2(2000);
    v_vUsrPDataName2 varchar2(2000);
  
    v_vUsrPDataTitle    varchar2(2000);
    v_vUsrPDataUnit     varchar2(2000);
    v_vUsrPDataSquadron varchar2(2000);
    v_vUsrPDataPhone    varchar2(2000);
  
    --patient personal information
    v_vPatPDataFirstName  varchar2(2000);
    v_vPatPDataLastName   varchar2(2000);
    v_vPatPDataSSN        varchar2(2000);
    v_vPatPDataCity       varchar2(2000);
    v_vPatPDataPostalCode varchar2(2000);
    v_vPatPDataHomePhone  varchar2(2000);
    v_vPatPDataWorkPhone  varchar2(2000);
    v_dtPatPDataDOB       date;
    v_vPWDCheck           varchar2(4000);
  
    v_vCUserName1    varchar2(2000);
    v_vCUsername2    varchar2(2000);
    v_vUNCheck       varchar2(2000);
    v_nResetPassword number;
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
    po_nUserID        := 0;
    v_nFXUserID       := 0;
    v_vPWDCheck       := '';
    v_nResetPassword  := 0;
  
    -- make sure the user only updates his password
    begin
      select count(t.fx_user_id)
        into v_nUserCount
        from tbicds.fx_user t
       where t.fx_user_id = pi_nUserID
         and t.user_name = pi_vUserName;
    exception
      when others then
        po_nStatusCode    := 1;
        po_vStatusComment := '1. Invalid User Name/Password';
        return;
    end;
  
    -- if no records were found the user was trying to update someone else
    if v_nUserCount = 0 and pi_nUserID > 0 then
      po_nStatusCode    := 1;
      po_vStatusComment := 'You may only change your password.';
      return;
    end if;
  
    --check for vaild current password
    begin
      select nvl(t.fx_user_id, 0),
             date_password_changed,
             PREV_PWD1,
             PREV_PWD2,
             PREV_PWD3,
             PREV_PWD4,
             PREV_PWD5,
             PREV_PWD6,
             PREV_PWD7,
             PREV_PWD8,
             PREV_PWD9,
             PREV_PWD10,
             nvl(RESET_PASSWORD, 0)
        into v_nFXUserID,
             v_dDatePasswordChanged,
             v_vPREV_PWD1,
             v_vPREV_PWD2,
             v_vPREV_PWD3,
             v_vPREV_PWD4,
             v_vPREV_PWD5,
             v_vPREV_PWD6,
             v_vPREV_PWD7,
             v_vPREV_PWD8,
             v_vPREV_PWD9,
             v_vPREV_PWD10,
             v_nResetPassword
        from tbicds.fx_user t
       where upper(t.user_name) = upper(pi_vUserName)
         and t.password = pi_vOldPassword;
    
    exception
      when others then
        po_nStatusCode    := 1;
        po_vStatusComment := '2. Invalid User Name/Password';
        return;
    end;
  
    if v_nFXUserID < 1 then
      po_nStatusCode    := 1;
      po_vStatusComment := '3. Invalid User Name/Password';
      return;
    end if;
  
    --validate the password against rules
  
    ValidatePassword(pi_vKey,
                     v_nFXUserID,
                     pi_vUserName,
                     pi_vOldPassword,
                     pi_vPassword,
                     pi_vCOldPassword,
                     pi_vCPassword,
                     pi_vCUserName,
                     v_nResetPassword,
                     po_nStatusCode,
                     po_vStatusComment);
    if po_nStatusCode != 0 then
      return;
    end if;
  
    --save the current password as a past password
    update tbicds.fx_user
       set prev_pwd1  = pi_vOldPassword,
           prev_pwd2  = v_vPREV_PWD1,
           prev_pwd3  = v_vPREV_PWD2,
           prev_pwd4  = v_vPREV_PWD3,
           prev_pwd5  = v_vPREV_PWD4,
           prev_pwd6  = v_vPREV_PWD5,
           prev_pwd7  = v_vPREV_PWD6,
           prev_pwd8  = v_vPREV_PWD7,
           prev_pwd9  = v_vPREV_PWD8,
           prev_pwd10 = v_vPREV_PWD9
     where lower(user_name) = lower(pi_vUserName)
       and password = pi_vOldPassword;
    commit;
  
    --update the users password to the new one
    update tbicds.fx_user
       set password              = pi_vPassword,
           is_locked             = 0,
           is_inactive           = 0,
           date_modified         = sysdate,
           updated_by            = pi_nUserID,
           reset_password        = 0,
           date_password_changed = sysdate,
           login_attempts        = 0
     where lower(user_name) = lower(pi_vUserName)
       and password = pi_vOldPassword;
    commit;
  
    --now login with this new password
    Login(pi_vSessionID,
          pi_vSessionClientIP,
          pi_nUserID,
          pi_vUserName,
          pi_vPassword,
          pi_vCert,
          po_nUserID,
          po_vDBSessionID,
          po_nTimeout,
          po_nStatusCode,
          po_vStatusComment);
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '163 - An error occurred while changing password, Please contact your system administrator.';
  end;

  /*used for signing notes etc.*/
  procedure Sign(pi_vSessionID       in varchar2,
                 pi_vSessionClientIP in varchar2,
                 pi_nUserID          in number,
                 pi_vUserName        in varchar2,
                 pi_vPassword        in varchar2,
                 po_vProviderID      out varchar2,
                 po_nUserType        out number,
                 po_nStatusCode      out number,
                 po_vStatusComment   out varchar2)
  
   is
  v_vStat varchar2(4000);
  v_nStat number;
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
    po_vProviderID    := '';
  
    select u.provider_id, r.user_type
      into po_vProviderID, po_nUserType
      from tbicds.fx_user t, tbicds.app_user u, tbicds.fx_user_rights r
     where t.fx_user_id = u.fx_user_id
       and r.fx_user_id = u.fx_user_id
       and t.user_name = pi_vUserName
       and t.password = pi_vPassword;
  
    if po_vProviderID = '' then
    
      --add an audit record
    /*  insert into tbicds.fx_audit
        (db_session_id,
         client_ip,
         fx_user_id,
         audit_date,
         audit_name,
         audit_data)
      values
        (pi_vSessionID,
         pi_vSessionClientIP,
         pi_nUserID,
         sysdate,
         'SIGN',
         'FAIL=' || pi_vUserName);*/
         
      begin
      
        SysLogAuditTransaction(pi_vSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               1,
                               'SIGN_FAILED'
                               || '|' || 'FAILED',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
    end if;
    
  
  exception
    when others then
      po_nStatusCode := 9;
      --po_vStatusComment := '164 - An error occurred while signing, Please contact your system administrator.';
    
      po_vStatusComment := 'Invalid user name/password';
    
      --add an audit record
      /*insert into tbicds.fx_audit
        (db_session_id,
         client_ip,
         fx_user_id,
         audit_date,
         audit_name,
         audit_data)
      values
        (pi_vSessionID,
         pi_vSessionClientIP,
         pi_nUserID,
         sysdate,
         'SIGN',
         'FAIL=' || pi_vUserName);*/
      
        begin
      
        SysLogAuditTransaction(pi_vSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               1,
                               'SIGN_FAILED'
                               || '|' || 'FAILED',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
    
  end;

  /*login this is the version that requires a username and password
  after a successful login the persons CAC will be associated with
  this account*/
  procedure Login(pi_vSessionID       in varchar2,
                  pi_vSessionClientIP in varchar2,
                  pi_nUserID          in number, --not used but passed in to maintain consistant default param list
                  pi_vUserName        in varchar2,
                  pi_vPassword        in varchar2,
                  pi_vCert            in varchar2,
                  po_nUserID          out number,
                  po_vDBSessionID     out varchar2,
                  po_nTimeout         out number,
                  po_nStatusCode      out number,
                  po_vStatusComment   out varchar2) 
  is
  
    v_nFXUserID        number;
    v_nFXUserChangePWD number;
    v_nFXUserInactive  number;
    v_nFXUserLocked    number;
  
    v_vDBSessionID    varchar2(4000);
    v_nCurrAttempts   number;
    v_nCount          number;
    v_nCurrIPAttempts number;
    v_nIPIsLocked     number;
    v_dtIPlocked      date;
    v_nIPLockPeriod   number;
    v_dtIPCheck       date;
    v_dtExpires       date;
    v_dtLastLogin     date;
  
    v_nMAX_ACCOUT_LOGIN_ATTEMPTS number;
    v_nMAX_IP_LOGIN_ATTEMPTS     number;
    v_nMAX_IP_LOGIN_TIMEOUT      number;
    v_nStatusCode                number;
    v_vStatus                    varchar2(4000);
    v_vContent                   varchar2(4000);
    v_vAccountCert               varchar2(4000);
  
    v_vstat                      varchar2(4000);
    v_nstat                      number;
    
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    po_nUserID     := 0;
    v_vDBSessionID := '';
  
    v_nFXUserID        := 0;
    v_nFXUserChangePWD := 0;
    v_nFXUserInactive  := 0;
    v_nFXUserLocked    := 0;
  
    v_vDBSessionID    := '';
    v_nCurrAttempts   := 0;
    v_nCount          := 0;
    v_nCurrIPAttempts := 0;
    v_nIPIsLocked     := 0;
    v_nIPLockPeriod   := 0;
    v_dtIPCheck       := sysdate;
    v_vAccountCert    := '';
  
    --
    v_nMAX_ACCOUT_LOGIN_ATTEMPTS := 3;
    v_nMAX_IP_LOGIN_ATTEMPTS     := 10;
    v_nMAX_IP_LOGIN_TIMEOUT      := 20;
  
    --
    --check to see if we are IP locked
    --
    begin
    
      --is the ip locked
      select nvl(t.is_locked, 0)
        into v_nIPIsLocked
        from tbicds.fx_iplogin_attempts t
       where t.client_ip = pi_vSessionClientIP;
    
      --time period in mins to lock
      select nvl(t.lock_period, v_nMAX_IP_LOGIN_TIMEOUT)
        into v_nIPLockPeriod
        from tbicds.fx_iplogin_attempts t
       where t.client_ip = pi_vSessionClientIP;
    
      --date locked
      select nvl(t.date_last_attempt, sysdate)
        into v_dtIPlocked
        from tbicds.fx_iplogin_attempts t
       where t.client_ip = pi_vSessionClientIP;
      if v_nIPIsLocked > 0 then
      
        --if the current date/time > (lock time + lock period)
        v_dtIPCheck := v_dtIPlocked + v_nIPLockPeriod / 1440;
        if sysdate > v_dtIPCheck then
        
          --if we are no longer ip locked clear the
          --fx_iplogin_attempts entry
          delete from tbicds.fx_iplogin_attempts
           where client_ip = pi_vSessionClientIP;
          commit;
        
        else
        
          po_nUserID        := '0';
          po_nStatusCode    := 6;
          po_vStatusComment := 'IP Address Locked!';
          return;
        
        end if;
      
      end if;
    
    exception
      when others then
        v_nIPIsLocked := 0;
    end;
  
    --login
    begin
    
      --get the user id and status info about the account
      select nvl(t.fx_user_id, 0),
             nvl(t.reset_password, 0),
             nvl(t.is_inactive, 0),
             nvl(t.is_locked, 0),
             t.date_password_changed,
             t.date_last_login
        into v_nFXUserID,
             v_nFXUserChangePWD,
             v_nFXUserInactive,
             v_nFXUserLocked,
             v_dtExpires,
             v_dtLastLogin
       
        from tbicds.fx_user t
       where upper(t.user_name) = upper(pi_vUserName)
         and t.password = pi_vPassword;
    
    exception
      when others then
      
        v_nFXUserID := 0;
      
    end;
  
    if v_nFXUserID > 0 then
    
      --check to see if this user is locked...
      if v_nFXUserLocked > 0 then
        po_nUserID        := '0';
        po_nStatusCode    := 2;
        po_vStatusComment := 'Your account is locked!';
        return;
      end if;
    
      --check to see if the user is inactive
      if v_nFXUserInactive > 0 then
        po_nUserID        := '0';
        po_nStatusCode    := 3;
        po_vStatusComment := 'Your account is inactive!';
        return;
      end if;
    
      --check the date_password_changed value and compare it
      --to the rules for pwd expiration...
      if v_dtExpires < trunc(sysdate) - 60 then
      
        po_nUserID        := '0';
        po_nStatusCode    := 9;
        po_vStatusComment := 'Your account has expired! Please contact your System Administrator to reset your password. ';
        return;
      
      end if;
    
      --make sure the user has logged in in the last 35 days otherwise they are expired
      if v_dtLastLogin < trunc(sysdate) - 35 and
         v_dtExpires < trunc(sysdate) - 35 then
      
        po_nUserID        := '0';
        po_nStatusCode    := 9;
        po_vStatusComment := 'Your account has expired due to inactivity! Please contact your System Administrator to reset your password. ';
        return;
      
      end if;
    
      --make sure there is not already a cert attached to this account
      if v_vAccountCert is not null then
        if v_vAccountCert != pi_vCert then
        
          po_nUserID        := '0';
          po_nStatusCode    := 9;
          po_vStatusComment := 'There is already a certificate associated with this account! Please contact your System Administrator to reset your password. ';
          return;
        
        end if;
      end if;
    
      --update the cert so that we autologin next time
     
      --reset the fx_user status info
      update tbicds.fx_user
         set is_locked       = 0,
             is_inactive     = 0,
             date_last_login = sysdate,
             flogin_attempts = login_attempts,
             login_attempts  = 0,
             LAST_LOGIN_IP   = pi_vSessionClientIP
       where fx_user_id = v_nFXUserID;
      commit;
    
      --reset the ip login attempts
      delete from tbicds.fx_iplogin_attempts
       where client_ip = pi_vSessionClientIP;
      commit;
    
      --set the timeout
      po_nTimeOut := 15;
      begin
      
        select nvl(t.session_timeout, 15)
          into po_nTimeout
          from tbicds.fx_user t
         where fx_user_id = v_nFXUserID;
      exception
        when others then
        
          po_nTimeOut := 0;
        
      end;
    
      --check to see if the user needs to change pwd
      if v_nFXUserChangePWD > 0 then
        po_nStatusCode    := 4;
        po_vStatusComment := 'Please Change Password!';
        return;
      end if;
    
      --get a new db session id:
      v_vDBSessionID := '';
      select t.SID || DBMS_CRYPTO.RandomBytes(3) || t.SERIAL# || t.USER# ||
             DBMS_CRYPTO.RandomBytes(3) || userenv('sessionid')
        into v_vDBSessionID
        from sys.v_$session t
       where t.audsid = userenv('sessionid');
    
      --clean up any old sessions, users can only login once!!!
      delete from tbicds.fx_session where fx_user_id = v_nFXUserID;
      commit;
      delete from tbicds.fx_session where db_session_id = v_vDBSessionID;
      commit;
      delete from tbicds.fx_session_value
       where db_session_id = v_vDBSessionID;
      commit;
    
      --insert a record into fx_session
      insert into tbicds.fx_session
        (fx_user_id,
         web_session_id,
         db_session_id,
         date_created,
         date_last_action,
         expired,
         client_ip)
      values
        (v_nFXUserID,
         pi_vSessionID,
         v_vDBSessionID,
         sysdate,
         sysdate,
         0,
         pi_vSessionClientIP);
    
      commit;
    
      --add an audit record for the success
    /*  insert into tbicds.fx_audit
        (db_session_id,
         client_ip,
         fx_user_id,
         audit_date,
         audit_name,
         audit_data)
      values
        (v_vDBSessionID,
         pi_vSessionClientIP,
         v_nFXUserID,
         sysdate,
         'LOGIN',
         'SUCCESS');
    
      commit;*/
      begin
      
        SysLogAuditTransaction(v_vDBSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               0,
                               'LOGIN'
                               || '|' || 'SUCCESS',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
    
      --return the user id
      po_nUserID      := v_nFXUserID;
      po_vDBSessionID := v_vDBSessionID;
    
    else
    
      po_nUserID        := '0';
      po_nStatusCode    := 1;
      po_vStatusComment := 'Invalid user name/password';
    
      --did we fail the login but have a valid user name?
      select count(*)
        into v_nCount
        from tbicds.fx_user t
       where upper(t.user_name) = upper(pi_vUserName);
      if v_nCount > 0 then
      
        --get the number of current attempts
        begin
          select nvl(t.login_attempts, 0)
            into v_nCurrAttempts
            from tbicds.fx_user t
           where upper(t.user_name) = upper(pi_vUserName);
        exception
          when others then
            v_nCurrAttempts := 0;
        end;
      
        --increment number of login attempts
        v_nCurrAttempts := v_nCurrAttempts + 1;
      
        --update the fx_user record
        update tbicds.fx_user
           set login_attempts   = v_nCurrAttempts,
               LAST_FLOGIN_IP   = pi_vSessionClientIP,
               LAST_FLOGIN_DATE = sysdate
         where upper(user_name) = upper(pi_vUserName);
      
        --check to see if we need to lock the account
        if v_nCurrAttempts >= v_nMAX_ACCOUT_LOGIN_ATTEMPTS then
        
          update tbicds.fx_user
             set is_locked = 1
           where upper(user_name) = upper(pi_vUserName);
          commit;
        
          po_nUserID        := '0';
          po_nStatusCode    := 7;
          po_vStatusComment := 'Invalid user name/password, Account Locked!';
        
        end if;
      
      else
      
        --attempting to login with a bad user name
        --need to track ip address and lock that ip
        --for a specified period of time
        v_nCount := 0;
        select count(*)
          into v_nCount
          from tbicds.FX_IPLOGIN_ATTEMPTS t
         where client_ip = pi_vSessionClientIP;
        if v_nCount > 0 then
        
          --get the number of attempts from this ip
          begin
            select login_attempts
              into v_nCurrIPAttempts
              from tbicds.FX_IPLOGIN_ATTEMPTS
             where client_ip = pi_vSessionClientIP;
          exception
            when others then
              v_nCurrIPAttempts := 0;
          end;
        
          --increment attempts
          v_nCurrIPAttempts := v_nCurrIPAttempts + 1;
        
          --update last attempt and date
          update tbicds.FX_IPLOGIN_ATTEMPTS
             set date_last_attempt = sysdate,
                 login_attempts    = v_nCurrIPAttempts
           where client_ip = pi_vSessionClientIP;
          commit;
        
          --check and lock if necessary
          if v_nCurrIPAttempts >= v_nMAX_IP_LOGIN_ATTEMPTS then
          
            update tbicds.FX_IPLOGIN_ATTEMPTS
               set is_locked = 1
             where client_ip = pi_vSessionClientIP;
            commit;
          
            po_nUserID        := '0';
            po_nStatusCode    := 3;
            po_vStatusComment := 'Invalid user name/password, IP Address Locked!';
          
            --email the SA and let them know...
            v_vContent := '';
            v_vContent := 'IP Address ' || pi_vSessionClientIP || ' ';
            v_vContent := v_vContent ||
                          'attempted to login 10 times with invalid user account information! ';
          end if;
        
        else
        
          --first bad ip attempt
          insert into tbicds.FX_IPLOGIN_ATTEMPTS
            (client_ip,
             login_attempts,
             date_last_attempt,
             is_locked,
             lock_period)
          values
            (pi_vSessionClientIP, 1, sysdate, 0, v_nMAX_IP_LOGIN_TIMEOUT);
          commit;
        
        end if;
      
      end if;
    
      --add an audit record for the fail
      /*insert into tbicds.fx_audit
        (db_session_id,
         client_ip,
         fx_user_id,
         audit_date,
         audit_name,
         audit_data)
      values
        (v_vDBSessionID,
         pi_vSessionClientIP,
         -1,
         sysdate,
         'LOGIN',
         'FAIL=' || pi_vUserName);*/
         
      begin
      
        SysLogAuditTransaction(v_vDBSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               1,
                               'LOGIN_FAILED'
                               || '|' || 'FAILED',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
    
    end if;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '165 - An error occurred while logging in, Please contact your system administrator.';
    
      --add an audit record
      /*insert into tbicds.fx_audit
        (db_session_id,
         client_ip,
         fx_user_id,
         audit_date,
         audit_name,
         audit_data)
      values
        (v_vDBSessionID,
         pi_vSessionClientIP,
         -1,
         sysdate,
         'LOGIN',
         'FAIL=' || pi_vUserName);*/
         
       begin
      
        SysLogAuditTransaction(v_vDBSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               1,
                               'LOGIN_FAILED'
                               || '|' || 'FAILED',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
      
  end;

  /*audit page acceess*/
  procedure AuditPageAccess(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vPageName        in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2)
  
   is
    v_nCount        number;
    v_nPageUserType number;
    v_nPageRights   number;
    v_nUserType     number;
    v_nUserRights   number;
    v_nSessionCount number;
    v_nPageActive   number;
    v_nPageLoggedIn number;
    v_nStat         number;
    v_vStat         varchar2(4000);
  
  begin
    v_nSessionCount := 0;
    v_nPageUserType := 0;
    v_nPageRights   := 0;
    v_nUserType     := 0;
    v_nUserRights   := 0;
    v_nPageLoggedIn := 0;
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nCount := 0;
  
    select nvl(t.user_rights, 0),
           nvl(t.user_type, 0),
           nvl(t.active, 1),
           nvl(t.is_logged_in, 0)
      into v_nPageRights, v_nPageUserType, v_nPageActive, v_nPageLoggedIn
      from tbicds.fx_page_access t
     where t.page_name = pi_vPageName;
  
    /*insert into tbicds.fx_audit
      (db_session_id,
       client_ip,
       fx_user_id,
       audit_date,
       audit_name,
       audit_data)
    values
      (pi_vSessionID,
       pi_vSessionClientIP,
       pi_nUserID,
       sysdate,
       'PAGE_ACCESS: ' || pi_vPageName,
       '');*/
       
      begin
      
        SysLogAuditTransaction(pi_vSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               0,
                               'PAGE_ACCESS: ' 
                               || '|' || pi_vSessionClientIP
                               || '|' || pi_nUserID
                               || '|' || pi_vPageName
                               || '|' || 'SUCCESS',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
  
    commit;
  
    -- There are some pages disabled in this version
    if v_nPageActive = 0 then
    
      --if we get here then we need to fail
      po_nStatusCode    := 1;
      po_vStatusComment := 'You are not authorized to view this page!';
    
      /*insert into tbicds.fx_audit
        (db_session_id,
         client_ip,
         fx_user_id,
         audit_date,
         audit_name,
         audit_data)
      values
        (pi_vSessionID,
         pi_vSessionClientIP,
         pi_nUserID,
         sysdate,
         'FAILED_PAGE_ACCESS: ' || pi_vPageName,
         '');*/
         
      begin
      
        SysLogAuditTransaction(pi_vSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               1,
                               'FAILED_PAGE_ACCESS: ' 
                               || '|' || pi_vSessionClientIP
                               || '|' || pi_nUserID
                               || '|' || pi_vPageName
                               || '|' || 'FAILED',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
    
      commit;
      return;
    
    end if;
  
    --allow access to everyone -not logged in
    if (v_nPageLoggedIn = 0) then
      --we are done
      return;
    end if;
  
    --allow access to everyone logged in
    if (v_nPageRights = 0) and (v_nPageUserType = 0) then
      --we are done
      return;
    end if;
  
    --
    --
    --all other pages from this point on require you to be logged in
    --and have some kind of permission
    --
    --
  
    --check that we have a valid user id
    if pi_nUserID < 1 then
    
      --if we get here then we need to fail
      po_nStatusCode    := 1;
      po_vStatusComment := 'You are not authorized to view this page!';
    
      /*insert into tbicds.fx_audit
        (db_session_id,
         client_ip,
         fx_user_id,
         audit_date,
         audit_name,
         audit_data)
      values
        (pi_vSessionID,
         pi_vSessionClientIP,
         pi_nUserID,
         sysdate,
         'FAILED_PAGE_ACCESS: ' || pi_vPageName,
         '');*/
         
        begin
      
        SysLogAuditTransaction(pi_vSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               1,
                               'FAILED_PAGE_ACCESS: ' 
                               || '|' || pi_vSessionClientIP
                               || '|' || pi_nUserID
                               || '|' || pi_vPageName
                               || '|' || 'FAILED',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
  
      commit;
      return;
    
    end if;
  
    --check that we have a valid session record
    select count(*)
      into v_nSessionCount
      from tbicds.fx_session t
     where t.fx_user_id = pi_nUserID
       and t.expired = 0;
    if v_nSessionCount != 1 then
    
      --if we get here then we need to fail
      po_nStatusCode    := 1;
      po_vStatusComment := 'You are not authorized to view this page!';
    
      /*insert into tbicds.fx_audit
        (db_session_id,
         client_ip,
         fx_user_id,
         audit_date,
         audit_name,
         audit_data)
      values
        (pi_vSessionID,
         pi_vSessionClientIP,
         pi_nUserID,
         sysdate,
         'FAILED_PAGE_ACCESS: ' || pi_vPageName,
         '');*/
       
      begin
      
         SysLogAuditTransaction(pi_vSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               1,
                               'FAILED_PAGE_ACCESS: ' 
                               || '|' || pi_vSessionClientIP
                               || '|' || pi_nUserID
                               || '|' || pi_vPageName
                               || '|' || 'FAILED',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
      
      commit;
      return;
    
    end if;
  
    --otherwise we must check
    select t.user_type, t.user_rights
      into v_nUserType, v_nUserRights
      from tbicds.fx_user_rights t
     where t.fx_user_id = pi_nUserID;
  
    if (((bitand(v_nUserRights, v_nPageRights) > 0) or v_nPageRights = 0) and
       ((bitand(v_nUserType, v_nPageUserType) > 0) or v_nPageUserType = 0))
    
     then
      return;
    end if;
  
    --if we get here then we need to fail
    po_nStatusCode    := 1;
    po_vStatusComment := 'You are not authorized to view this page!';
  
    /*insert into tbicds.fx_audit
      (db_session_id,
       client_ip,
       fx_user_id,
       audit_date,
       audit_name,
       audit_data)
    values
      (pi_vSessionID,
       pi_vSessionClientIP,
       pi_nUserID,
       sysdate,
       'FAILED_PAGE_ACCESS: ' || pi_vPageName,
       '');*/
       
       begin
      
        SysLogAuditTransaction(pi_vSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               1,
                               'FAILED_PAGE_ACCESS: ' 
                               || '|' || pi_vSessionClientIP
                               || '|' || pi_nUserID
                               || '|' || pi_vPageName
                               || '|' || 'FAILED',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
  
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '166 - An error occurred while auditing page access , Please contact your system administrator.';
    
      /*insert into tbicds.fx_audit
        (db_session_id,
         client_ip,
         fx_user_id,
         audit_date,
         audit_name,
         audit_data)
      values
        (pi_vSessionID,
         pi_vSessionClientIP,
         pi_nUserID,
         sysdate,
         'FAILED_PAGE_ACCESS: ' || pi_vPageName,
         '');*/
      
        begin
      
         SysLogAuditTransaction(pi_vSessionID,
                               pi_vSessionClientIP,
                               pi_nUserID,
                               1,
                               'FAILED_PAGE_ACCESS: ' 
                               || '|' || pi_vSessionClientIP
                               || '|' || pi_nUserID
                               || '|' || pi_vPageName
                               || '|' || 'FAILED',
                                v_nStat,
                                v_vStat);
                             
    
      exception
      when others then
        null;
      end;
    
      commit;
  end;

  /*audits a transaction by encrypting the clob passed in 
  and storing the params and clob in the fx_audit table*/
  procedure AuditTransaction(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vKey             in varchar2,
                             pi_vSPName          in varchar2,
                             pi_clAuditXML       in clob,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2)
  
   is
  
    v_nCount   number := 0;
    v_nCounter number := 1;
  
    --the encrypted audit text
    v_vAudit varchar(32767) := '';
  
    v_vWorking varchar(32767) := '';
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nCount := 0;
  
    --if audit is < 4001 chars then enc the whole thing
    --otherwise enc it in pieces seperated by _ most calls will 
    --be under 4K!!!
    if length(pi_clAuditXML) < 2001 then
    
      v_vAudit := ic_utl_sec.encryptData(substr(pi_clAuditXML, 1, 2000),
                                             pi_vKey,
                                             pi_vSessionClientIP);
    else
    
      --get a working string
      v_vWorking := pi_clAuditXML;
      v_vAudit   := '';
    
      --how many times do we need to chunk it
      v_nCount := length(v_vWorking) / 1000;
      v_nCount := ceil(v_nCount);
    
      --loop and chunk
      for v_nCounter IN 1 .. v_nCount loop
      
        if v_nCounter = v_nCount then
        
          --last one so grab the rest
          v_vAudit := v_vAudit ||
                      ic_utl_sec.encryptData(v_vWorking,
                                                 pi_vKey,
                                                 pi_vSessionClientIP);
          v_vAudit := v_vAudit || '|';
        
        else
        
          --grab 1000 chars  
          v_vAudit := v_vAudit ||
                      ic_utl_sec.encryptData(substr(v_vWorking, 1, 1000),
                                                 pi_vKey,
                                                 pi_vSessionClientIP);
          v_vAudit := v_vAudit || '|';
        
          --adjust working to next 4k group
          v_vWorking := substr(v_vWorking, 1001);
        
        end if;
      end loop;
    
    end if;
  
    --insert the record into the audit table
    insert into tbicds.fx_audit
      (db_session_id,
       client_ip,
       fx_user_id,
       audit_date,
       audit_name,
       audit_data)
    values
      (pi_vSessionID,
       pi_vSessionClientIP,
       pi_nUserID,
       sysdate,
       pi_vSPName,
       v_vAudit);
  
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '167 - An error occurred while auditing a transaction, Please contact your system administrator.';
  end;

  
  /*Log Off, clears session from the db*/
  procedure LogOff(pi_vSessionID       in varchar2,
                   pi_vSessionClientIP in varchar2,
                   pi_nUserID          in number,
                   po_nStatusCode      out number,
                   po_vStatusComment   out varchar2)
  
   is
    v_nCount number;
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nCount := 0;
  
    --clean up any old sessions, users can only login once!!!
    delete from tbicds.fx_session where fx_user_id = pi_nUserID;
    commit;
    delete from tbicds.fx_session where db_session_id = pi_vSessionID;
    commit;
    delete from tbicds.fx_session_value
     where db_session_id = pi_vSessionID;
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '168 - An error occurred while logging off, Please contact your system administrator.';
  end;

  /*gets an fx_user record given the encrypted uid*/
  procedure GetFXUserRS(pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        pi_vEncUID          in varchar2,
                        po_nStatusCode      out number,
                        po_vStatusComment   out varchar2,
                        rs                  out RetRefCursor) 
  is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    open rs for
      select t.*,
             --less than or equal to zero means we are expired!
             floor(60 - (trunc(sysdate) - t.date_password_changed)) as days_till_expiration
        from tbicds.fx_user t
       where user_name = pi_vEncUID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '169 - An error occurred while retrieving a user record, Please contact your system administrator.';
  end;

  /*insert a record into the fx_user table
  and update the fx_user_id in the app_user table*/
  procedure InsertFXUser(pi_vSessionID       in varchar2,
                         pi_vSessionClientIP in varchar2,
                         pi_nUserID          in number,
                         pi_vKey             in varchar2,
                         pi_vProviderID      in varchar2,
                         pi_vUserName        in varchar2,
                         pi_vPassword        in varchar2,
                         pi_nAccountLocked   in number,
                         pi_nAccountInactive in number,
                         
                         pi_vCOldPassword in varchar2,
                         pi_vCPassword    in varchar2,
                         pi_vCUserName    in varchar2,
                         
                         po_nFXUserID      out number,
                         po_nStatusCode    out number,
                         po_vStatusComment out varchar2)
  
   is
    v_nCount    number;
    v_nFXUserID number;
    dtSys       date;
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nCount    := 0;
    v_nFXUserID := 0;
    dtSys       := sysdate;
  
    --get a new user id from the sequence
    --
    select tbicds.seqFXUserID.Nextval into v_nFXUserID from dual;
  
    insert into tbicds.fx_user
      (fx_user_id,
       user_name,
       is_locked,
       is_inactive,
       date_created,
       date_modified,
       updated_by,
       reset_password,
       date_password_changed,
       date_last_login,
       session_timeout,
       login_attempts,
       password)
    values
      (v_nFXUserID, --fx_user_id,
       pi_vUserName, --user_name,
       pi_nAccountLocked, --is_locked,
       pi_nAccountInactive, --is_inactive,
       dtSys, --date_created,
       dtSys, --date_modified,
       pi_nUserID, --updated_by,
       1, --ALWAYS MUST reset_password,
       dtSys, --date_password_changed,
       dtSys, --date_last_login,
       15, --session_timeout,
       0, --login_attempts,
       pi_vPassword --password
       );
  
    commit;
  
    --update the app_user table fx id
    update tbicds.app_user
       set fx_user_id = v_nFXUserID
     where provider_id = pi_vProviderID;
    commit;
  
    --create user record in fx_user_rights
    insert into tbicds.fx_user_rights
      (fx_user_id, user_rights, read_only)
    values
      (v_nFXUserID, 0, 0);
    commit;
  
    --have to insert the record before validating
    ValidatePassword(pi_vKey,
                     v_nFXUserID,
                     pi_vUserName,
                     'NA',
                     pi_vPassword,
                     'NA',
                     pi_vCPassword,
                     pi_vCUserName,
                     1,
                     po_nStatusCode,
                     po_vStatusComment);
  
    if po_nStatusCode != 0 then
    
      delete from tbicds.fx_user where fx_user_id = v_nFXUserID;
      commit;
    
      po_nFXUserID := 0;
    
    end if;
  
    po_nFXUserID := v_nFXUserID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '170 - An error occurred while inserting a user, Please contact your system administrator.';
  end;

  /*update an fx_user record*/
  procedure UpdateFXUser(pi_vSessionID       in varchar2,
                         pi_vSessionClientIP in varchar2,
                         pi_nUserID          in number,
                         pi_nFXUserID        in number,
                         pi_vProviderID      in varchar2,
                         pi_vUserName        in varchar2,
                         pi_vPassword        in varchar2,
                         pi_nAccountLocked   in number,
                         pi_nAccountInactive in number,
                         po_nStatusCode      out number,
                         po_vStatusComment   out varchar2)
  
   is
    v_nCount  number;
    dtSys     date;
    v_currpwd varchar2(4000);
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nCount  := 0;
    dtSys     := sysdate;
    v_currpwd := '';
  
    --update date_password_changed if the user changed the pwd
    select password
      into v_currpwd
      from tbicds.fx_user
     where fx_user_id = pi_nFXUserID;
    if v_currpwd != pi_vPassword then
    
      update tbicds.fx_user
         set date_password_changed = dtSys
       where fx_user_id = pi_nFXUserID;
      commit;
    
    end if;
  
    update tbicds.fx_user
       set is_locked      = pi_nAccountLocked,
           is_inactive    = pi_nAccountInactive,
           date_modified  = dtSys,
           updated_by     = pi_nUserID,
           reset_password = 1, --always MUST CHANGE PASSWORD
           password       = pi_vPassword
     where fx_user_id = pi_nFXUserID;
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '171 - An error occurred while updating a user, Please contact your system administrator.';
  end;

  /*update fx_user_rights*/
  procedure UpdateFXUserRights(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_nFxUserID        in number,
                               pi_nUserType        in number,
                               pi_nUserRights      in number,
                               pi_nUserReadOnly    in number,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2) 
 is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    update tbicds.fx_user_rights
       set user_rights = pi_nUserRights,
           read_only   = pi_nUserReadOnly,
           user_type   = pi_nUserType
     where fx_user_id = pi_nFxUserID;
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_FX_SEC.UpdateSuatUserRights(): ';
  end;

  /*update an fx_user record pwd*/
  procedure UpdateFXUserPWD(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vKey             in varchar2,
                            pi_nFXUserID        in number,
                            pi_vUserName        in varchar2,
                            pi_vPassword        in varchar2,
                            pi_nAccountLocked   in number,
                            pi_nAccountInactive in number,
                            
                            pi_vCPassword in varchar2,
                            pi_vCUserName in varchar2,
                            
                            po_nStatusCode    out number,
                            po_vStatusComment out varchar2)
  
   is
    v_nCount  number;
    dtSys     date;
    v_currpwd varchar2(4000);
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nCount  := 0;
    dtSys     := sysdate;
    v_currpwd := '';
  
    ValidatePassword(pi_vKey,
                     pi_nFXUserID,
                     pi_vUserName,
                     'NA',
                     pi_vPassword,
                     'NA',
                     pi_vCPassword,
                     pi_vCUserName,
                     1,
                     po_nStatusCode,
                     po_vStatusComment);
  
    if po_nStatusCode != 0 then
      return;
    end if;
  
    --update date_password_changed if the user changed the pwd
    select password
      into v_currpwd
      from tbicds.fx_user
     where fx_user_id = pi_nFXUserID;
    if v_currpwd != pi_vPassword then
    
      update tbicds.fx_user
         set date_password_changed = dtSys
       where fx_user_id = pi_nFXUserID;
      commit;
    
    end if;
  
    update tbicds.fx_user
       set is_locked      = pi_nAccountLocked,
           is_inactive    = pi_nAccountInactive,
           date_modified  = dtSys,
           updated_by     = pi_nUserID,
           reset_password = 1, --always MUST CHANGE PASSWORD
           password       = pi_vPassword
     where fx_user_id = pi_nFXUserID;
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '172 - An error occurred while resetting a password, Please contact your system administrator.';
  end;

  /*update an fx_user options*/
  procedure UpdateFXUserOptions(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nFXUserID        in number,
                                pi_nAccountLocked   in number,
                                pi_nAccountInactive in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2)
  
   is
    dtSys date;
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    dtSys := sysdate;
  
    update tbicds.fx_user
       set is_locked     = pi_nAccountLocked,
           is_inactive   = pi_nAccountInactive,
           date_modified = dtSys,
           updated_by    = pi_nUserID
     where fx_user_id = pi_nFXUserID;
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '173 - An error occurred while updating a user account, Please contact your system administrator.';
  end;

  /*gets an Username and Password given the providerid*/
  procedure GetFXUsernamePasswordRS(pi_vSessionID       in varchar2,
                                    pi_vSessionClientIP in varchar2,
                                    pi_nUserID          in number,
                                    pi_vProviderID      in varchar2,
                                    po_nStatusCode      out number,
                                    po_vStatusComment   out varchar2,
                                    rs                  out RetRefCursor) 
  is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    open rs for
      select * from tbicds.fx_user t where fx_user_id = pi_nUserID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '174 - An error occurred while retrieving a user account, Please contact your system administrator.';
  end;

  /* gets an FXUserID given the providerid */
  procedure GetFXUserIdRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vProviderID      in varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor)
  
   is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    open rs for
      select fx_user_id
        from tbicds.app_user t
       where provider_id = pi_vProviderID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '175 - An error occurred while retrieving a user ID, Please contact your system administrator.';
  end;

  /*gets a FXUserID given the providerid*/
  procedure CheckFXUserRecRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vProviderID      in varchar2,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor) 
   is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    open rs for
      select count(f.fx_user_id) as FXUserCount
        from tbicds.fx_user f
       where f.fx_user_id =
             (select s.fx_user_id
                from tbicds.app_user s
               where s.provider_id = pi_vProviderID);
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '176 - An error occurred while checking a user record, Please contact your system administrator.';
  end;

  /* gets user's selected security questions */
  procedure GetUserQuestions(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               --
                               pi_vUsername in varchar2,
                               --                                 
                               po_nStatusCode    out number,
                               po_vStatusComment out varchar2,
                               rs                out RetRefCursor) 
                               
    is
    
      v_nFXUserID number := 0;
      v_nCount    number := 0;  
      
      v_nCurrIPAttempts number;
      v_nIPIsLocked     number;
      v_dtIPlocked      date;
      v_nIPLockPeriod   number;
      v_dtIPCheck       date;
      v_dtExpires       date;
      v_dtLastLogin     date;
      
      v_nMAX_IP_LOGIN_ATTEMPTS     number;
      v_nMAX_IP_LOGIN_TIMEOUT      number;
    
    begin    
         
      v_nCurrIPAttempts := 0;
      v_nIPIsLocked     := 0;
      v_nIPLockPeriod   := 0;
      v_dtIPCheck       := sysdate;
      
      v_nMAX_IP_LOGIN_ATTEMPTS     := 10;
      v_nMAX_IP_LOGIN_TIMEOUT      := 20;
    
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
    
      --
      --check to see if we are IP locked
      --
      begin
      
        --is the ip locked
        select nvl(t.is_locked, 0)
          into v_nIPIsLocked
          from tbicds.fx_iplogin_attempts t
         where t.client_ip = pi_vSessionClientIP;
      
        --time period in mins to lock
        select nvl(t.lock_period, v_nMAX_IP_LOGIN_TIMEOUT)
          into v_nIPLockPeriod
          from tbicds.fx_iplogin_attempts t
         where t.client_ip = pi_vSessionClientIP;
      
        --date locked
        select nvl(t.date_last_attempt, sysdate)
          into v_dtIPlocked
          from tbicds.fx_iplogin_attempts t
         where t.client_ip = pi_vSessionClientIP;
        if v_nIPIsLocked > 0 then
        
          --if the current date/time > (lock time + lock period)
          v_dtIPCheck := v_dtIPlocked + v_nIPLockPeriod / 1440;
          if sysdate > v_dtIPCheck then
          
            --if we are no longer ip locked clear the
            --fx_iplogin_attempts entry
            delete from tbicds.fx_iplogin_attempts
             where client_ip = pi_vSessionClientIP;
            commit;
          
          else
          
            open rs
             for select (select 0 from dual) as fx_user_id,
                        (select '' from dual) as question_1,
                        (select '' from dual) as question_2,
                        (select 0 from dual) as is_locked,
                        (select 0 from dual) as is_locked
                   from dual;
                 
            po_nStatusCode    := 6;
            po_vStatusComment := 'IP Address Locked!';
            return;
          
          end if;
        
        end if;
      
      exception
        when others then
          v_nIPIsLocked := 0;
      end;
      
      select count(*)
        into v_nCount
        from tbicds.fx_user t
       where t.user_name = pi_vUsername;
    
      if v_nCount > 0 then
        select fx_user_id
          into v_nFXUserID
          from tbicds.fx_user t
         where t.user_name = pi_vUsername;
      else
        --attempting to login with a bad user name
          --need to track ip address and lock that ip
          --for a specified period of time
          v_nCount := 0;
          select count(*)
            into v_nCount
            from tbicds.FX_IPLOGIN_ATTEMPTS t
           where client_ip = pi_vSessionClientIP;
          if v_nCount > 0 then
          
            --get the number of attempts from this ip
            begin
              select login_attempts
                into v_nCurrIPAttempts
                from tbicds.FX_IPLOGIN_ATTEMPTS
               where client_ip = pi_vSessionClientIP;
            exception
              when others then
                v_nCurrIPAttempts := 0;
            end;
          
            --increment attempts
            v_nCurrIPAttempts := v_nCurrIPAttempts + 1;
          
            --update last attempt and date
            update tbicds.FX_IPLOGIN_ATTEMPTS
               set date_last_attempt = sysdate,
                   login_attempts    = v_nCurrIPAttempts
             where client_ip = pi_vSessionClientIP;
            commit;
          
            --check and lock if necessary
            if v_nCurrIPAttempts >= v_nMAX_IP_LOGIN_ATTEMPTS then
            
              update tbicds.FX_IPLOGIN_ATTEMPTS
                 set is_locked = 1
               where client_ip = pi_vSessionClientIP;
              commit;
            
              open rs
             for select (select 0 from dual) as fx_user_id,
                        (select '' from dual) as question_1,
                        (select '' from dual) as question_2,
                        (select 0 from dual) as is_locked,
                        (select 0 from dual) as is_locked
                   from dual;
                   
              po_nStatusCode    := 6;
              po_vStatusComment := 'Invalid username, IP Address Locked!';
   
            end if;
          
          else
          
            --first bad ip attempt
            insert into tbicds.FX_IPLOGIN_ATTEMPTS
              (client_ip,
               login_attempts,
               date_last_attempt,
               is_locked,
               lock_period)
            values
              (pi_vSessionClientIP, 1, sysdate, 0, v_nMAX_IP_LOGIN_TIMEOUT);
            commit;
          
          end if;
      end if;
    
      --open recordset
      open rs for
        select v_nFXUserID as fx_user_id,
               (select question
                  from tbicds.stat_sec_questions q
                 where q.question_id in
                       (select sq.question_id_1
                          from tbicds.fx_sec_questions sq
                         where fx_user_id = v_nFXUserID)) as question_1,
               
               (select question
                  from tbicds.stat_sec_questions q
                 where q.question_id in
                       (select sq.question_id_2
                          from tbicds.fx_sec_questions sq
                         where fx_user_id = v_nFXUserID)) as question_2,
               
               (select t.is_locked
                  from tbicds.fx_user t
                 where t.fx_user_id = v_nFXUserID) as is_locked,
                 
                 (select v_nIPIsLocked from dual) as ip_locked
          from dual; 
          
          
    
    exception
      when others then
        po_nStatusCode    := 1;
        po_vStatusComment := 'PCK_FX_SEC.GetUserQuestions(): ';
    end;

  /* updates user's selected security questions */
  procedure UpdateSecQuestions(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 
                                 pi_nQuestionID_1 in number,
                                 pi_vAnswer_1     in varchar2,
                                 
                                 pi_nQuestionID_2 in number,
                                 pi_vAnswer_2     in varchar2,
                                 
                                 pi_nQuestionID_3 in number,
                                 pi_vAnswer_3     in varchar2,
                                 
                                 po_nStatusCode    out number,
                                 po_vStatusComment out varchar2) 
                                 
    is
    
      v_bIsUpdate boolean := false;
      v_nCount    number := 0;
    
    begin
    
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
    
      select count(*)
        into v_nCount
        from tbicds.fx_sec_questions f
       where f.fx_user_id = pi_nUserID;
    
      if v_nCount > 0 then
        v_bIsUpdate := true;
      end if;
    
      if v_bIsUpdate then
        update tbicds.fx_sec_questions q
           set q.question_id_1 = pi_nQuestionID_1,
               q.answer_1      = pi_vAnswer_1,
               q.question_id_2 = pi_nQuestionID_2,
               q.answer_2      = pi_vAnswer_2
        --q.question_id_3 = pi_nQuestionID_3,
        --q.answer_3      = pi_vAnswer_3
         where q.fx_user_id = pi_nUserID;
      else
        insert into tbicds.fx_sec_questions q
          (fx_user_id,
           question_id_1,
           answer_1,
           question_id_2,
           answer_2,
           question_id_3,
           answer_3)
        values
          (pi_nUserID,
           pi_nQuestionID_1,
           pi_vAnswer_1,
           pi_nQuestionID_2,
           pi_vAnswer_2,
           null,
           null);
      end if;
    
      commit;
    
    exception
      when others then
        po_nStatusCode    := 1;
        po_vStatusComment := 'PCK_FX_SEC.UpdateSecQuestions(): ';
    end;

  /* checks answers submited for the challenge questions */
  procedure CheckSecurityQuestions(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     
                                     --pi_nQuestionID_1 in number,
                                     pi_vAnswer_1 in varchar2,
                                     
                                     --pi_nQuestionID_2 in number,
                                     pi_vAnswer_2 in varchar2,
                                     
                                     --pi_nQuestionID_3 in number,
                                     pi_vAnswer_3 in varchar2,
                                     
                                     po_nStatusCode    out number,
                                     po_vStatusComment out varchar2) 
     is
    
      v_nValidQ1 number := 0;
      v_nValidQ2 number := 0;
      v_nValidQ3 number := 0;
    
      v_nAttempts number := 0;
    
    begin
    
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
    
      select count(*)
        into v_nValidQ1
        from tbicds.fx_sec_questions q
       where q.fx_user_id = pi_nUserID
         and q.answer_1 = pi_vAnswer_1;
    
      select count(*)
        into v_nValidQ2
        from tbicds.fx_sec_questions q
       where q.fx_user_id = pi_nUserID
         and q.answer_2 = pi_vAnswer_2;
    
      
      --select count(*)
      --  into v_nValidQ3
      --  from tbicds.fx_sec_questions q
      -- where q.fx_user_id = pi_nUserID
      --   and q.answer_3 = pi_vAnswer_3;
      
      if (v_nValidQ1 + v_nValidQ2 + v_nValidQ3) >= 2 then
      
        update tbicds.fx_sec_questions t
           set t.answer_attempts = 0, t.last_updated = sysdate
         where t.fx_user_id = pi_nUserID;
        commit;
      
        po_nStatusCode    := 0; --0 = success
        po_vStatusComment := '';
      
      else
      
        select t.answer_attempts
          into v_nAttempts
          from tbicds.fx_sec_questions t
         where t.fx_user_id = pi_nUserID;
      
        v_nAttempts := v_nAttempts + 1;
      
        update tbicds.fx_sec_questions t
           set t.answer_attempts = v_nAttempts, t.last_updated = sysdate
         where t.fx_user_id = pi_nUserID;
        commit;
      
        if v_nAttempts >= 3 then
          update tbicds.fx_user t
             set t.is_locked       = 1,
                 t.flogin_attempts = v_nAttempts,
                 t.last_updated    = sysdate
           where t.fx_user_id = pi_nUserID;
          commit;
        
          po_nStatusCode    := 9; --9 = account locked
          po_vStatusComment := 'Your security answer attempts have exceeded that set by the system, so your account has been locked. ';
          po_vStatusComment := po_vStatusComment ||
                               'Please contact the system administrator to reactivate your login. ';
          po_vStatusComment := po_vStatusComment ||
                               'Security answer is invalid.';
          return;
        else
          po_nStatusCode    := 1; --1 = invalid answer
          po_vStatusComment := 'Security answer is invalid.';
          return;
        end if;
      
      end if;
    
    exception
      when others then
        po_nStatusCode    := 1;
        po_vStatusComment := 'PCK_FX_SEC.CheckSecurityQuestions(): ';
    end;

  /* reset account  password */
  procedure ResetPassword(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vKey             in varchar2,
                          pi_nFXUserID        in number,
                          pi_vUserName        in varchar2,
                          pi_vPassword        in varchar2,
                          pi_vCPassword       in varchar2,
                          pi_vCUserName       in varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2)
  
   is
    v_nCount  number;
    dtSys     date;
    v_currpwd varchar2(4000);
  
  begin
  
    --default status to good
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nCount  := 0;
    dtSys     := sysdate;
    v_currpwd := '';
  
    pck_fx_sec.ValidatePassword(pi_vKey,
                                pi_nFXUserID,
                                pi_vUserName,
                                'NA',
                                pi_vPassword,
                                'NA',
                                pi_vCPassword,
                                pi_vCUserName,
                                1,
                                po_nStatusCode,
                                po_vStatusComment);
    if po_nStatusCode != 0 then
      return;
    end if;
  
    --update date_password_changed if the user changed the pwd
    select password
      into v_currpwd
      from tbicds.fx_user
     where fx_user_id = pi_nFXUserID;
    if v_currpwd != pi_vPassword then
    
      update tbicds.fx_user
         set date_password_changed = dtSys,
             last_updated          = sysdate,
             last_updated_by       = pi_nFXUserID
       where fx_user_id = pi_nFXUserID;
      commit;
    
    end if;
  
    update tbicds.fx_user
       set is_locked       = 0,
           is_inactive     = 0,
           date_modified   = dtSys,
           updated_by      = pi_nFXUserID,
           reset_password  = 0,
           password        = pi_vPassword,
           last_updated    = sysdate,
           last_updated_by = pi_nFXUserID
     where fx_user_id = pi_nFXUserID;
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '178 - An error occurred while updating a patients password, Please contact your system administrator.';
  end;

  /* Gets security questions */
  procedure GetSecurityQuestions(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_nQuestionGrp     in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor) 
  is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    open rs for
      select *
        from stat_sec_questions q
       where q.active = 1
         and q.question_group = pi_nQuestionGrp;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_FX_SEC.GetSecurityQuestions(): ';
  end;

end;
/

prompt
prompt Creating package body PCK_FX_SEC_PATIENT
prompt ========================================
prompt
create or replace package body tbicds.PCK_FX_SEC_PATIENT is
  
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   /* checks if a portal account exists for the patient */
   procedure CheckPatientFXUserRecRS( pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      pi_vKey             in varchar2,
                                      pi_vPatientID       in varchar2,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2,
                                      rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select count(f.fx_user_id) as FXUserCount '
                || 'from tbicds.fx_user f '
                || 'where f.fx_user_id = ('
                || 'select p.fx_user_id '
                || 'from tbicds.patient_demographics p '
                || 'where p.patient_id = :P0 '
                || ') ';
      open rs for v_vSql using pi_vPatientID;
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := '182 - An error occurred while checking a patients account, Please contact your system administrator.';
   end;

   /* gets a FXUserID given the patient */
   procedure GetPatientFXUserIdRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  pi_vKey in varchar2,
                                  pi_vPatientID      in varchar2,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select fx_user_id from tbicds.patient_demographics t where patient_id = :P0 ';
      open rs for v_vSql using pi_vPatientID;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := '181 - An error occurred while retrieving a patients account, Please contact your system administrator.';
   end;

   /* gets the encrypted username/password pair for the patient */
   procedure GetPatientFXUsernamePasswordRS(pi_vSessionID       in varchar2,
                                            pi_vSessionClientIP in varchar2,
                                            pi_nUserID          in number,
                                            pi_vKey in varchar2,
                                            pi_vPatientID       in varchar2,
                                            po_nStatusCode      out number,
                                            po_vStatusComment   out varchar2,
                                            rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select * '
                || 'from tbicds.fx_user t '
                || 'where fx_user_id = ('
                || 'select fx_user_id from tbicds.patient_demographics t where patient_id = :P0 '
                || ') ';
      open rs for v_vSql using pi_vPatientID;

   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := '180 - An error occurred while retrieving patients account information, Please contact your system administrator.';
   end;

   /* updates the patient portal account */
   procedure InsertPatientFXUser (pi_vSessionID              in varchar2,
                                  pi_vSessionClientIP        in varchar2,
                                  pi_nUserID                 in number,
                                  pi_vKey in varchar2,
                                  pi_vPatientID              in varchar2,
                                  pi_vUserName               in varchar2,
                                  pi_vPassword               in varchar2,
                                  pi_nAccountLocked          in number,
                                  pi_nAccountInactive        in number,
                                  pi_vCOldPassword           in varchar2,
                                  pi_vCPassword              in varchar2,
                                  pi_vCUserName              in varchar2,   
                                  po_nFXUserID               out number,
                                  po_nStatusCode             out number,
                                  po_vStatusComment          out varchar2)
   is
      v_vSql                               varchar2(4000);
      v_nCount            number;
      v_nFXUserID         number;
      dtSys               date;
      v_nUserType         number := 32768;
   begin
      --default status to good
      po_nStatusCode := 0; --0 = success
      po_vStatusComment := '';

      v_nCount := 0;
      v_nFXUserID := 0;
      dtSys := sysdate;

      --get a new user id from the sequence
      --
      v_vSql := 'select tbicds.seqFXUserID.Nextval from dual';
      execute immediate v_vSql into v_nFXUserID;

      v_vSql := 'insert into tbicds.fx_user ('
                || 'fx_user_id, user_name, is_locked, is_inactive, '
                || 'date_created, date_modified, updated_by, reset_password, date_password_changed, '
                || 'date_last_login, session_timeout, login_attempts, password, last_updated, '
                || 'last_updated_by) '
                || 'values ('
                || ':P0, :P1, :P2, :P3, :P4, :P5, :P6, :P7, :P8, :P9, '
                || ':P10, :P11, :P12, :P13, :P14, :P15) ';
      execute immediate v_vSql using
         v_nFXUserID,              --fx_user_id,
         pi_vUserName,             --user_name,
         pi_nAccountLocked,        --is_locked,
         pi_nAccountInactive,      --is_inactive,
         dtSys,                    --date_created,
         dtSys,                    --date_modified,
         pi_nUserID,               --updated_by,
         1,                        --ALWAYS MUST reset_password,
         dtSys,                    --date_password_changed,
         dtSys,                    --date_last_login,
         30,                       --session_timeout,
         0,                        --login_attempts,
         pi_vPassword,              --password
         sysdate,
         pi_nUserID;
      commit;
      
      v_vSql := 'insert into tbicds.fx_user_rights ('
                || 'fx_user_id, user_rights, read_only, user_type) '
                || 'values ('
                || ':P0, :P1, :P2, :P3) ';
      execute immediate v_vSql using v_nFXUserID, 0, 0, v_nUserType;
      commit;

      --update the app_user table fx id
      v_vSql := 'update tbicds.patient_demographics set '
                || 'fx_user_id = :P0, '
                || 'last_updated = sysdate, '
                || 'last_updated_by = :P1 '
                || 'where patient_id = :P2 ';
      execute immediate v_vSql using v_nFXUserID, pi_nUserID, pi_vPatientID;
      commit;
      
      --have to insert the record before validating
      pck_fx_sec.ValidatePassword(
                        pi_vKey,
                        v_nFXUserID,
                        pi_vUserName,
                        'NA',
                        pi_vPassword,
                        'NA',
                        pi_vCPassword,
                        pi_vCUserName,
                        1,
                        po_nStatusCode,
                        po_vStatusComment);
       
      if po_nStatusCode != 0 then
         --clear the fx record for the patient
         v_vSql := 'update tbicds.patient_demographics set fx_user_id = null where fx_user_id = :P0';
         execute immediate v_vSql using v_nFXUserID;
         
         --remove the fx_user from the db
         v_vSql := 'delete from tbicds.fx_user where fx_user_id = :P0';
         execute immediate v_vSql using v_nFXUserID;
         commit;
         
         v_vSql := 'delete from tbicds.fx_user_rights where fx_user_id = :P0';
         execute immediate v_vSql using v_nFXUserID;
         commit;
         
         po_nFXUserID := 0;
      end if;

      po_nFXUserID := v_nFXUserID;

   exception
      when others
      then
         po_nStatusCode := 1;
         po_vStatusComment := '177 - An error occurred while inserting a pateint user record, Please contact your system administrator.';
   end;

   /* updates the patient portal account password*/
   procedure UpdatePatientFXUserPWD(pi_vSessionID              in varchar2,
                                    pi_vSessionClientIP        in varchar2,
                                    pi_nUserID                 in number,
                                    pi_vKey in varchar2,
                                    pi_nFXUserID               in number,
                                    pi_vUserName               in varchar2,
                                    pi_vPassword               in varchar2,
                                    pi_nAccountLocked          in number,
                                    pi_nAccountInactive        in number,
                                    pi_vCPassword              in varchar2,
                                    pi_vCUserName              in varchar2,
                                    po_nStatusCode             out number,
                                    po_vStatusComment          out varchar2)
   is
      v_vSql                               varchar2(4000);
      v_nCount            number;
      dtSys               date;
      v_currpwd           varchar2(4000);
   begin
      --default status to good
      po_nStatusCode := 0; --0 = success
      po_vStatusComment := '';

      v_nCount := 0;
      dtSys := sysdate;
      v_currpwd := '';

      pck_fx_sec.ValidatePassword(pi_vKey,
                                  pi_nFXUserID,
                                  pi_vUserName,
                                  'NA',
                                  pi_vPassword,
                                  'NA',
                                  pi_vCPassword,
                                  pi_vCUserName,
                                  1,
                                  po_nStatusCode,
                                  po_vStatusComment);
      if po_nStatusCode != 0 then
         return;
      end if;
                        
      --update date_password_changed if the user changed the pwd
      v_vSql := 'select password from tbicds.fx_user where fx_user_id = :P0';
      execute immediate v_vSql into v_currpwd using pi_nFXUserID;
      
      if v_currpwd != pi_vPassword then
         v_vSql := 'update tbicds.fx_user set '
                   || 'date_password_changed = :P0, '
                   || 'last_updated = sysdate, '
                   || 'last_updated_by = :P1 '
                   || 'where fx_user_id = :P2 ';
         execute immediate v_vSql using dtSys, pi_nUserID, pi_nFXUserID;
         commit;
      end if;

      v_vSql := 'update tbicds.fx_user set '
                || 'is_locked = :P0, '
                || 'is_inactive = :P1, '
                || 'date_modified = :P2, '
                || 'updated_by = :P3, '
                || 'reset_password = 1, ' --always MUST CHANGE PASSWORD
                || 'password = :P4, '
                || 'last_updated = sysdate, '
                || 'last_updated_by = :P5 '
                || 'where fx_user_id = :P6 ';
      execute immediate v_vSql using pi_nAccountLocked, pi_nAccountInactive, dtSys, pi_nUserID, pi_vPassword, pi_nUserID, pi_nFXUserID;
      commit;

   exception
      when others
      then
         po_nStatusCode := 1;
         po_vStatusComment := '178 - An error occurred while updating a patients password, Please contact your system administrator.';
   end;

   /* updates the patient portal account options */
   procedure UpdatePatientFXUserOptions(pi_vSessionID              in varchar2,
                                        pi_vSessionClientIP        in varchar2,
                                        pi_nUserID                 in number,
                                        pi_nFXUserID               in number,
                                        pi_nAccountLocked          in number,
                                        pi_nAccountInactive        in number,
                                        po_nStatusCode             out number,
                                        po_vStatusComment          out varchar2)
   is
      v_vSql                               varchar2(4000);
      v_nCount            number;
      dtSys               date;
   begin
      --default status to good
      po_nStatusCode := 0; --0 = success
      po_vStatusComment := '';

      dtSys := sysdate;

      v_vSql := 'update tbicds.fx_user set '
                || 'is_locked = :P0, '
                || 'is_inactive = :P1, '
                || 'date_modified = :P2, '
                || 'updated_by = :P3, '
                || 'last_updated = sysdate, '
                || 'last_updated_by = :P4 '
                || 'where fx_user_id = :P5 ';
      execute immediate v_vSql using pi_nAccountLocked, pi_nAccountInactive, dtSys, pi_nUserID, pi_nUserID, pi_nFXUserID;
      commit;
      
      -- when the account is re-activated, reset the answer attempts number in fx_sec_question
      if pi_nAccountLocked = 0 then
         v_vSql := ' update tbicds.fx_sec_questions t set '
                   || 't.answer_attempts = 0, '
                   || 't.last_updated = sysdate '
                   || 'where t.fx_user_id = :P0 ';
         execute immediate v_vSql using pi_nFXUserID;
         commit;
      end if;

   exception
      when others
      then
         po_nStatusCode := 1;
         po_vStatusComment := '179 - An error occurred while updating a patients user account, Please contact your system administrator.';
   end;
 

end;
/

prompt
prompt Creating package body PCK_INSTRUMENT_RESPONSES
prompt ==============================================
prompt
create or replace package body tbicds.PCK_INSTRUMENT_RESPONSES is

/* Copyright 2015 Intellica Corporation.  

This software is protected by FAR Subpart 27.4 - Rights in Data and Copyrights and 
international treaties.  The software was produced by Intellica Corporation of 
San Antonio, Texas for the Veterans Administration (VA) under Contract Number 
VA118-14-C-0015, Project Number TAC-16-28335 and Project Title, 
'Traumatic Brain Injury Clinical Decision Support (TBI CDS) Implementation'.  
Contract dates: 8 May 2014 - 4 January 2016.  This software was finalized 
and uploaded to the VA's Open Source Electronic Health Record Alliance (OSEHRA) 
on 31 December 2015.  Unauthorized reproduction or distribution of this software 
or any portion of it may result in severe civil and criminal penalties and will 
be prosecuted to the maximum possible extent of the law.

For licensing information contact:  info@intellicacorp.com 
*/

  /*get an export score value given the data and a filter*/
  function fnGetExportScoreValue(pi_vDataValue  in varchar2,
                                 pi_vStatFilter in varchar2) return varchar2
  is
    v_rs              PCK_COMMON.refCursor;
    v_vSQL            varchar2(32767) := '';
    po_vResponseValue varchar2(32767) := '';

  begin
  
    v_vSQL := v_vSQL || ' select t.score_value ';
    v_vSQL := v_vSQL || '   from INTAKE_STATIC_DATA t ';
    v_vSQL := v_vSQL || '  where t.active = 1 ';
    v_vSQL := v_vSQL || '    and t.data_value = ''' || pi_vDataValue || '''';
    v_vSQL := v_vSQL || '    and ';
    v_vSQL := v_vSQL || pi_vStatFilter;
  
    open v_rs for v_vSQL;
    loop
      fetch v_rs
        into  po_vResponseValue;

      exit when v_rs%notfound;
    end loop;
    close v_rs;
    
    
    return po_vResponseValue;
  
  exception
    when others then
      return '';
  end;
  
  /* Write instrument responses to the database. */
  procedure InsertInstrumentResponse(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     
                                     pi_vPatientID     in varchar2,
                                     pi_nIntakeID      in number,
                                     pi_nMID           in number,
                                     pi_nTID           in number,
                                     pi_nQID           in number,
                                     pi_nRID           in number,
                                     pi_nScoreValue    in number,
                                     pi_vResponseValue in varchar2,
                                     
                                     po_nStatusCode    out number,
                                     po_vStatusComment out varchar2)
  
   is
    v_vSQL               varchar2(4000);
    v_nResponseType      number := null;
    v_dtResponseDateTime date := sysdate;
    v_vIdentifier        varchar2(24) := null;
  
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
    
    --get identifier for the response
    begin
      select identifier
        into v_vIdentifier
        from intake_response t
       where t.mid = pi_nMID
         and t.tid = pi_nTID
         and t.qid = pi_nQID
         and t.rid = pi_nRID;
    exception 
      when others then
      v_vIdentifier := null;     
    end;
  
    v_vSQL := v_vSQL || ' insert into DATA_INTAKE_RESPONSES ';
    v_vSQL := v_vSQL || '  (PATIENT_ID, ';
    v_vSQL := v_vSQL || '   INTAKE_ID, ';
    v_vSQL := v_vSQL || '   RID, ';
    v_vSQL := v_vSQL || '   MID, ';
    v_vSQL := v_vSQL || '   TID, ';
    v_vSQL := v_vSQL || '   QID, ';
    v_vSQL := v_vSQL || '   RESPONSE_TYPE, ';
    v_vSQL := v_vSQL || '   RESPONSE_VALUE, ';
    v_vSQL := v_vSQL || '   SCORE_VALUE, ';
    v_vSQL := v_vSQL || '   RESPONSE_DATETIME, ';
    v_vSQL := v_vSQL || '   IDENTIFIER) ';
    v_vSQL := v_vSQL || ' values ';
    v_vSQL := v_vSQL || '   (:V_PATIENT_ID, ';
    v_vSQL := v_vSQL || '   :V_INTAKE_ID, ';
    v_vSQL := v_vSQL || '   :V_RID, ';
    v_vSQL := v_vSQL || '   :V_MID, ';
    v_vSQL := v_vSQL || '   :V_TID, ';
    v_vSQL := v_vSQL || '   :V_QID, ';
    v_vSQL := v_vSQL || '   :V_RESPONSE_TYPE, ';
    v_vSQL := v_vSQL || '   :V_RESPONSE_VALUE, ';
    v_vSQL := v_vSQL || '   :V_SCORE_VALUE, ';
    v_vSQL := v_vSQL || '   :V_RESPONSE_DATETIME, ';
    v_vSQL := v_vSQL || '   :v_vIDENTIFIER) ';
  
    --get response type from intake_response table
    begin
      select t.response_type
        into v_nResponseType
        from intake_response t
       where t.mid = pi_nMID
         and t.tid = pi_nTID
         and t.qid = pi_nQID
         and t.rid = pi_nRID;
    exception
      when others then
        v_nResponseType := null;
    end;
  
    execute immediate v_vSQL
      using pi_vPatientID, 
            pi_nIntakeID, 
            pi_nRID, 
            pi_nMID, 
            pi_nTID, 
            pi_nQID, 
            v_nResponseType, 
            pi_vResponseValue, 
            pi_nScoreValue, 
            v_dtResponseDateTime,
            v_vIdentifier;

    --AUDIT TRAIL
    v_vSQL := replace(v_vSQL, 'DATA_INTAKE_RESPONSES', 'DATA_INTAKE_RESPONSES_AUDIT');
    execute immediate v_vSQL
      using pi_vPatientID, 
            pi_nIntakeID, 
            pi_nRID, 
            pi_nMID, 
            pi_nTID, 
            pi_nQID, 
            v_nResponseType, 
            pi_vResponseValue, 
            pi_nScoreValue, 
            v_dtResponseDateTime,
            v_vIdentifier;
              
    commit;
  
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := Sqlerrm;
  end;

  /* Get instruments responses by MID */
  procedure GetInstrumentResponsesRS(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     
                                     pi_vPatientID      in varchar2,
                                     --pi_nSiteID         in number,
                                     --pi_nClinicalProgID in number,
                                     --pi_nPathwayID      in number,
                                     pi_nMID            in number,
                                     pi_nIntakeID       in number,
                                     
                                     rs                out PCK_COMMON.refCursor,
                                     po_nStatusCode    out number,
                                     po_vStatusComment out varchar2) 
   is
  
    v_vSQL          varchar2(4000);
    v_nLastIntakeID number := 0;
  
  begin
    po_nStatusCode    := 0;
    po_vStatusComment := '';
  
    --v_vSQL := v_vSQL || '		select 	dr.*, ';
    v_vSQL := v_vSQL || 'select dr.PATIENT_ID,dr.INTAKE_ID,dr.RID,dr.MID,dr.TID,dr.QID,';
    v_vSQL := v_vSQL || '       dr.RESPONSE_TYPE,dr.RESPONSE_VALUE,ir.LABEL_POS,';
    v_vSQL := v_vSQL || '       case';
    v_vSQL := v_vSQL || '         when ir.display_type not in(4,22) and dr.SCORE_VALUE=0 and ir.score_value is null then ''''';
    v_vSQL := v_vSQL || '         when ir.display_type in(4,22) and dr.SCORE_VALUE=0 and ir.score_value is null and ir.stat_load_filter is null then ''''';
    v_vSQL := v_vSQL || '         when ir.display_type in(4,22) and dr.SCORE_VALUE=0 and ir.score_value is null and ir.stat_load_filter is not null then';
    v_vSQL := v_vSQL || '           pck_instrument_responses.fnGetExportScoreValue(dr.RESPONSE_VALUE, ir.stat_load_filter)';
    v_vSQL := v_vSQL || '         else to_char(dr.score_value) ';
    v_vSQL := v_vSQL || '       end as SCORE_VALUE,';
    v_vSQL := v_vSQL || '       dr.RESPONSE_DATETIME,dr.RESPONSE_TIME,dr.INTAKE_GROUP_ID,dr.IDENTIFIER,';
    v_vSQL := v_vSQL || '				im.module, ';
    v_vSQL := v_vSQL || '				it.topic, ';
    v_vSQL := v_vSQL || '				iq.question, ';
    v_vSQL := v_vSQL || '				ir.response as static_response, ';
    v_vSQL := v_vSQL || '				ir.display_type, ';
    v_vSQL := v_vSQL || '				ir.unit, ';
    v_vSQL := v_vSQL || '				di.complete_date ';
    v_vSQL := v_vSQL || '		from 	data_intake_responses dr, ';
    v_vSQL := v_vSQL || '				data_intake di, ';
    v_vSQL := v_vSQL || '				intake_module im, ';
    v_vSQL := v_vSQL || '				intake_topic it, ';
    v_vSQL := v_vSQL || '				intake_question iq, ';
    v_vSQL := v_vSQL || '				intake_response ir ';
  
    v_vSQL := v_vSQL || '		where 	dr.patient_id = :PATIENT_ID ';
    v_vSQL := v_vSQL || '		and 	dr.mid = :MID ';
    v_vSQL := v_vSQL || '		and 	dr.intake_id = :INTAKE_ID ';
    
    --data_intake
    v_vSQL := v_vSQL || '		and di.patient_id = dr.patient_id';
    v_vSQL := v_vSQL || '		and di.intake_id = dr.intake_id';
    v_vSQL := v_vSQL || '		and di.mid = dr.mid';
  
    --intake_module
    v_vSQL := v_vSQL || '		and 	dr.mid = im.mid ';
  
    --intake_topic
    v_vSQL := v_vSQL || '		and 	dr.mid = it.mid ';
    v_vSQL := v_vSQL || '		and 	dr.tid = it.tid ';
  
    --intake_question
    v_vSQL := v_vSQL || '		and 	dr.mid = iq.mid ';
    v_vSQL := v_vSQL || '		and 	dr.tid = iq.tid ';
    v_vSQL := v_vSQL || '		and 	dr.qid = iq.qid ';
  
    --intake_response
    v_vSQL := v_vSQL || '		and 	dr.mid = ir.mid ';
    v_vSQL := v_vSQL || '		and 	dr.tid = ir.tid ';
    v_vSQL := v_vSQL || '		and 	dr.qid = ir.qid ';
    v_vSQL := v_vSQL || '		and 	dr.rid = ir.rid ';
  
    v_vSQL := v_vSQL || '		order by dr.mid, ';
    v_vSQL := v_vSQL || '				dr.tid, ';
    v_vSQL := v_vSQL || '				dr.qid, ';
    v_vSQL := v_vSQL || '				dr.rid ';
  
    -- get lats intake_id for the instrument
    begin
    
      select max(t.intake_id)
        into v_nLastIntakeID
        from data_intake_responses t
       where t.patient_id = pi_vPatientID
         and t.mid = pi_nMID;
    
    exception
      when others then
        v_nLastIntakeID := 0;
    end;
  
    --open the cursor
    open rs for v_vSQL
      using pi_vPatientID, pi_nMID, pi_nIntakeID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;
  
  /* Get merged instruments responses */
  procedure GetMergedInstrumentResponsesRS(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     
                                     pi_vPatientID      in varchar2,
                                     pi_nMID            in number,
                                     pi_nIntakeID       in number,
                                     
                                     rs                out PCK_COMMON.refCursor,
                                     po_nStatusCode    out number,
                                     po_vStatusComment out varchar2) 
  is
  
  begin
    po_nStatusCode    := 0;
    po_vStatusComment := '';
  
    --open recordset
    open rs for
    select *
  from (select r.mid,
               r.tid,
               r.qid,
               r.rid,
               r.identifier,
               r.response_value,
               r.score_value,
               r.response_type,
               1 as is_selected
          from data_intake_responses r
         where r.patient_id = pi_vPatientID
           and r.mid = pi_nMID
           and r.intake_id = pi_nIntakeID
        
        union
        
        select ir.mid,
               ir.tid,
               ir.qid,
               ir.rid,
               ir.identifier,
               '' as response_value,
               to_number(ir.score_value),
               ir.response_type,
               0 as is_selected
          from intake_response ir
         where ir.mid = pi_nMID
           and ir.rid not in (select r.rid
                                from data_intake_responses r
                               where r.patient_id = pi_vPatientID
                                 and r.mid = pi_nMID
                                 and r.intake_id = pi_nIntakeID)
        
        ) a
 order by mid, tid, qid, rid;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

  /* Returns a recordset with the resolved intake logic variables*/
  PROCEDURE GetIntakeLogicVarRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vPatientID       in varchar2,
                                pi_vKey             in varchar2,
                                pi_nMID             in number,
                                rs                  out PCK_COMMON.refCursor,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2) 
   is
  
    v_vSQL     VARCHAR2(32767) := '';
    v_vQuery   VARCHAR2(4000);
    v_count    NUMBER := 0;
    v_varvalue VARCHAR2(24);
  
  BEGIN
  
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    FOR rec IN (SELECT *
                  FROM INTAKE_LOGICVAR_SQL t
                 where t.var_id in (select var_id
                                      from intake_module_variables v
                                     where v.mid = pi_nMID)) LOOP
      IF v_count > 0 THEN
        v_vSQL := v_vSQL || ' union ';
      END IF;
      v_vQuery := REPLACE(rec.LOAD_SQL,
                          '_PATIENT_ID',
                          '''' || pi_vPatientID || '''');
      v_vQuery := REPLACE(v_vQuery, '_ENCRYPT_KEY', '''' || pi_vKey || '''');
      v_vQuery := REPLACE(v_vQuery, '_MID', pi_nMID);
      BEGIN
        EXECUTE immediate v_vQuery
          INTO v_varvalue;
      EXCEPTION
        WHEN OTHERS THEN
          v_varvalue := '';
      END;
      v_vSQL  := v_vSQL || 'select ''' || rec.VAR_ID || ''' as VAR_ID, ''' ||
                 rec.IDENTIFIER || ''' as IDENTIFIER, ''' || v_varvalue ||
                 ''' as VAR_VALUE from dual';
      v_count := v_count + 1;
    END LOOP;
    OPEN rs FOR v_vSQL;
  
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := '';
  end;

  /*Get the score logic for the module*/
  procedure GetScoreLogicRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_nMID             in number,
                            rs                  out PCK_COMMON.refCursor,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2) 
  is
  
    v_vSQL varchar2(4000);
  
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || '  select mid, score_logic ';
    v_vSQL := v_vSQL || '    from intake_module ';
    v_vSQL := v_vSQL || '   where active = 1 ';
    v_vSQL := v_vSQL || '     and mid = :MID ';
  
    --open the cursor
    open rs for v_vSQL
      using pi_nMID;
  
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := '';
  end;

  /*get instruments for a patient*/
  PROCEDURE GetPatientInstrumentsRS(pi_vSessionID       IN VARCHAR2,
                                    pi_vSessionClientIP IN VARCHAR2,
                                    pi_nUserID          IN NUMBER,
                                    pi_vPatientID       IN VARCHAR2,
                                    rs                  OUT PCK_COMMON.refCursor,
                                    po_nStatusCode      OUT NUMBER,
                                    po_vStatusComment   OUT VARCHAR2) 
  is
  
  BEGIN
    po_nStatusCode    := 0;
    po_vStatusComment := '';
    --open the cursor
    OPEN rs FOR
    
      SELECT 0 AS status_id,
             'Unknown' AS status,
             t.patient_id,
             t.intake_id,
             t.mid,
             m.module,
             t.complete_date AS date_completed,
             t.score,
             '' AS interpretation,
             DECODE(t.complete, 0, 'No', 1, 'Yes') AS completed
        FROM data_intake t, intake_module m
       WHERE t.mid = m.mid
         AND t.patient_id = pi_vPatientID;
  
  EXCEPTION
    WHEN OTHERS THEN
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  END;
 
 /*****
 Remove ALL responses from previous time submitted 
 *****/
 procedure RemoveAllResponses(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vPatientID       in varchar2,
                              pi_nMID             in number,
                              pi_nIntakeID        in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2) 
 is
 
   v_vSQL varchar2(1000) := '';
 
 begin
   po_nStatusCode    := 0;
   po_vStatusComment := '';
   
   v_vSQL := v_vSQL || '  delete from data_intake_responses ';
   v_vSQL := v_vSQL || '    where patient_id = :pi_vPatientID ';
   v_vSQL := v_vSQL || '      and mid = :pi_nMID ';
   v_vSQL := v_vSQL || '      and intake_id = :pi_nIntakeID';
   
   execute immediate v_vSQL using pi_vPatientID, pi_nMID, pi_nIntakeID; 
   commit;
 
 exception
   when others then
     po_nStatusCode    := 1;
     po_vStatusComment := '';
 end;
 
 /*****
 Remove responses from previous time submitted
 not present in a new submittal of the instrument 
 *****/
 procedure RemovePrevResponses(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vPatientID       in varchar2,
                               pi_nMID             in number,
                               pi_nIntakeID        in number,
                               pi_vResponses       in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2) 
 is
 
   v_vSQL varchar2(1000) := '';
 
 begin
   po_nStatusCode    := 0;
   po_vStatusComment := '';
   
   v_vSQL := v_vSQL || '  delete from data_intake_responses ';
   v_vSQL := v_vSQL || '    where patient_id = :pi_vPatientID ';
   v_vSQL := v_vSQL || '      and mid = :pi_nMID ';
   v_vSQL := v_vSQL || '      and intake_id = :pi_nIntakeID ';
   v_vSQL := v_vSQL || '      and rid not in (' || pi_vResponses || ') '; 
   
   execute immediate v_vSQL using pi_vPatientID, pi_nMID, pi_nIntakeID; 
   commit;
 
 exception
   when others then
     po_nStatusCode    := 1;
     po_vStatusComment := '';
 end;
 
 /*remove a response from an intake*/
 procedure RemoveResponse(pi_vSessionID       in varchar2,
                         pi_vSessionClientIP in varchar2,
                         pi_nUserID          in number,
                         pi_vPatientID       in varchar2,
                         pi_nMID             in number,
                         pi_nIntakeID        in number,
                         pi_nRID             in number,
                         po_nStatusCode      out number,
                         po_vStatusComment   out varchar2) 
 is
 
   v_vSQL varchar2(1000) := '';
 
 begin
   po_nStatusCode    := 0;
   po_vStatusComment := '';
   
   v_vSQL := v_vSQL || '  delete from data_intake_responses ';
   v_vSQL := v_vSQL || '    where patient_id =  :pi_vPatientID ';
   v_vSQL := v_vSQL || '      and mid = :pi_nMID ';
   v_vSQL := v_vSQL || '      and intake_id = :pi_nIntakeID ';
   v_vSQL := v_vSQL || '      and rid = :pi_nRID'; 
   
   execute immediate v_vSQL using pi_vPatientID, pi_nMID, pi_nIntakeID, pi_nRID; 
   commit;
 
 exception
   when others then
     po_nStatusCode    := 1;
     po_vStatusComment := '';
 end;
 
 /*****  
 Inserts Instruments Scores
 *****/
 procedure InsertInstrumentScore(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                     
                                 pi_vPatientID       in varchar2,
                                 pi_nIntakeID        in number,
                                 pi_nMID             in number,
                                 pi_nSeriesID        in number,
                                 pi_nScore           in number,
                                 pi_vInterpret       in varchar2,
                                     
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2)
  
   is
    v_vSQL  varchar2(4000) := '';
  
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || '    insert ';
    v_vSQL := v_vSQL || '       into data_intake_score s ';
    v_vSQL := v_vSQL || '         (patient_id, '; 
    v_vSQL := v_vSQL || '         mid, '; 
    v_vSQL := v_vSQL || '         intake_id, '; 
    v_vSQL := v_vSQL || '         series, '; 
    v_vSQL := v_vSQL || '         score, '; 
    v_vSQL := v_vSQL || '         interpretation) ';
    v_vSQL := v_vSQL || '       values ';
    v_vSQL := v_vSQL || '         (:PATIENT_ID, '; 
    v_vSQL := v_vSQL || '         :MID, '; 
    v_vSQL := v_vSQL || '         :INTAKE_ID, '; 
    v_vSQL := v_vSQL || '         :SERIES_ID, '; 
    v_vSQL := v_vSQL || '         :SCORE, '; 
    v_vSQL := v_vSQL || '         :INTERPRETATION) ';
  
    
  execute immediate v_vSQL
      using pi_vPatientID, 
      pi_nMID, 
      pi_nIntakeID, 
      pi_nSeriesID, 
      pi_nScore, 
      pi_vInterpret; 
      
  --AUDIT TRAIL
  v_vSQL := replace(v_vSQL, 'data_intake_score', 'data_intake_score_audit');
  execute immediate v_vSQL
      using pi_vPatientID, 
      pi_nMID, 
      pi_nIntakeID, 
      pi_nSeriesID, 
      pi_nScore, 
      pi_vInterpret;
  
    commit;
  
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := '';
  end;
  
  /*Insert instrument score*/
  procedure InsertInstrumentScore(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                     
                                 pi_vPatientID       in varchar2,
                                 pi_nIntakeID        in number,
                                 pi_nMID             in number,
                                 pi_nSeriesID        in number,
                                 pi_nScore           in number,
                                 pi_vInterpret       in varchar2,
                                 pi_vDescription     in varchar2,
                                     
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2)
  
   is
    v_vSQL  varchar2(4000) := '';
  
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || '    insert ';
    v_vSQL := v_vSQL || '       into data_intake_score s ';
    v_vSQL := v_vSQL || '         (patient_id, '; 
    v_vSQL := v_vSQL || '         mid, '; 
    v_vSQL := v_vSQL || '         intake_id, '; 
    v_vSQL := v_vSQL || '         series, '; 
    v_vSQL := v_vSQL || '         score, '; 
    v_vSQL := v_vSQL || '         interpretation, ';
    v_vSQL := v_vSQL || '         description) ';
    v_vSQL := v_vSQL || '       values ';
    v_vSQL := v_vSQL || '         (:PATIENT_ID, '; 
    v_vSQL := v_vSQL || '         :MID, '; 
    v_vSQL := v_vSQL || '         :INTAKE_ID, '; 
    v_vSQL := v_vSQL || '         :SERIES_ID, '; 
    v_vSQL := v_vSQL || '         :SCORE, '; 
    v_vSQL := v_vSQL || '         :INTERPRETATION, ';
    v_vSQL := v_vSQL || '         :DESCRIPTION) ';
  
    
  execute immediate v_vSQL
      using pi_vPatientID, 
      pi_nMID, 
      pi_nIntakeID, 
      pi_nSeriesID, 
      pi_nScore, 
      pi_vInterpret,
      pi_vDescription; 
  
  --AUDIT TRAIL
  v_vSQL := replace(v_vSQL, 'data_intake_score', 'data_intake_score_audit');
  execute immediate v_vSQL
      using pi_vPatientID, 
      pi_nMID, 
      pi_nIntakeID, 
      pi_nSeriesID, 
      pi_nScore, 
      pi_vInterpret,
      pi_vDescription;
  
    commit;
  
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := '';
  end;
  
  /*Insert instrument score*/
  procedure InsertInstrumentScore(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                     
                                 pi_vPatientID       in varchar2,
                                 pi_nIntakeID        in number,
                                 pi_nMID             in number,
                                 pi_nSeriesID        in number,
                                 pi_nScore           in number,
                                 pi_vInterpret       in varchar2,
                                 pi_vDescription     in varchar2,
                                 pi_nSeverity        in number,
                                     
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2)
  
   is
    v_vSQL  varchar2(4000) := '';
  
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || '    insert ';
    v_vSQL := v_vSQL || '       into data_intake_score s ';
    v_vSQL := v_vSQL || '         (patient_id, '; 
    v_vSQL := v_vSQL || '         mid, '; 
    v_vSQL := v_vSQL || '         intake_id, '; 
    v_vSQL := v_vSQL || '         series, '; 
    v_vSQL := v_vSQL || '         score, '; 
    v_vSQL := v_vSQL || '         interpretation, ';
    v_vSQL := v_vSQL || '         description, ';
    v_vSQL := v_vSQL || '         severity) ';
    v_vSQL := v_vSQL || '       values ';
    v_vSQL := v_vSQL || '         (:PATIENT_ID, '; 
    v_vSQL := v_vSQL || '         :MID, '; 
    v_vSQL := v_vSQL || '         :INTAKE_ID, '; 
    v_vSQL := v_vSQL || '         :SERIES_ID, '; 
    v_vSQL := v_vSQL || '         :SCORE, '; 
    v_vSQL := v_vSQL || '         :INTERPRETATION, ';
    v_vSQL := v_vSQL || '         :DESCRIPTION, ';
    v_vSQL := v_vSQL || '         :SEVERITY) ';
  
    
  execute immediate v_vSQL
      using pi_vPatientID, 
      pi_nMID, 
      pi_nIntakeID, 
      pi_nSeriesID, 
      pi_nScore, 
      pi_vInterpret,
      pi_vDescription,
      pi_nSeverity; 
  
  --AUDIT TRAIL
  v_vSQL := replace(v_vSQL, 'data_intake_score', 'data_intake_score_audit');
  execute immediate v_vSQL
      using pi_vPatientID, 
      pi_nMID, 
      pi_nIntakeID, 
      pi_nSeriesID, 
      pi_nScore, 
      pi_vInterpret,
      pi_vDescription,
      pi_nSeverity; 
  
    commit;
  
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := '';
  end;
  
  /*****
  Delete Instrument Scores
  *****/
  procedure DeleteInstrumentScore(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP  in varchar2,
                                 pi_nUserID           in number,
                                     
                                 pi_vPatientID        in varchar2,
                                 pi_nIntakeID         in number,
                                 pi_nMID              in number,
                                     
                                 po_nStatusCode       out number,
                                 po_vStatusComment    out varchar2)
  
   is
    v_vSQL  varchar2(4000) := '';
  
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || ' delete ';
    v_vSQL := v_vSQL || '   from data_intake_score d ';
    v_vSQL := v_vSQL || '  where d.patient_id = :PATIENT_ID ';
    v_vSQL := v_vSQL || '    and d.mid = :MID ';
    v_vSQL := v_vSQL || '    and d.intake_id = :INTAKE_ID ';
  
    
  execute immediate v_vSQL
      using pi_vPatientID, 
      pi_nMID, 
      pi_nIntakeID; 
  
    commit;
  
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := '';
  end;

  /*****
  Gets recordset of instrument score and apply filter
  *****/
  procedure GetInstrumentScoresRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                       
                                  pi_vPatientID       in varchar2,
                                  pi_nMID             in number,
                                  pi_nIntakeID        in number,
                                  pi_nFilter          in number,
                                       
                                  rs                  out PCK_COMMON.refCursor,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2) 
 is
    v_vSQL          varchar2(4000);
  
  begin
    po_nStatusCode    := 0;
    po_vStatusComment := '';

 
    v_vSQL := v_vSQL || ' select * ';
    v_vSQL := v_vSQL || '   from (select t.*, ';
    v_vSQL := v_vSQL || '                im.module, ';
    v_vSQL := v_vSQL || '                m.date_completed ';
    v_vSQL := v_vSQL || '           from data_intake_score t, '; 
    v_vSQL := v_vSQL || '                pat_pw_event_module m, '; 
    v_vSQL := v_vSQL || '                intake_module im ';
    v_vSQL := v_vSQL || '          where t.patient_id = :PATIENT_ID ';
    v_vSQL := v_vSQL || '            and t.mid = :MID ';
    v_vSQL := v_vSQL || '            and t.patient_id = m.patient_id ';
    v_vSQL := v_vSQL || '            and t.mid = m.mid ';
    v_vSQL := v_vSQL || '            and t.intake_id = m.intake_id ';
    v_vSQL := v_vSQL || '            and t.mid = im.mid(+) ';
    
    --exclude FIM goal scores, they are not real scores!
    if pi_nMID = 4042 then
    
      v_vSQL := v_vSQL || ' and ((select rid ';
      v_vSQL := v_vSQL || '         from data_intake_responses ';
      v_vSQL := v_vSQL || '        where intake_id = t.intake_id ';
      v_vSQL := v_vSQL || '          and tid=1 ';
      v_vSQL := v_vSQL || '          and qid=1 ) != 21) ';
    
    end if;                
    
    --apply filter
    case
      when pi_nFilter = 0 then v_vSQL := v_vSQL || ' ';
      when pi_nFilter = 1 then v_vSQL := v_vSQL || ' and t.intake_id <= ' || pi_nIntakeID;
      when pi_nFilter = 2 then v_vSQL := v_vSQL || ' and t.intake_id = ' || pi_nIntakeID;
      when pi_nFilter = 3 then v_vSQL := v_vSQL || ' and m.status = 2 and t.intake_id <= ' || pi_nIntakeID;
    end case;
    
    v_vSQL := v_vSQL || '            ) a ';
    v_vSQL := v_vSQL || '  order by a.mid, a.series, date_completed, intake_id ';
    
    --open the cursor
    open rs for v_vSQL
      using pi_vPatientID, pi_nMID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;
  
  /*****
  Gets recordset of instrument score
  *****/
  procedure GetInstrumentScoresRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                     
                                 pi_vPatientID      in varchar2,
                                 pi_nMID            in number,
                                 pi_nIntakeID       in number,
                                     
                                 rs                out PCK_COMMON.refCursor,
                                 po_nStatusCode    out number,
                                 po_vStatusComment out varchar2) 
   is
  
    v_vSQL          varchar2(4000);
    v_nLastIntakeID number := 0;
  
  begin
    po_nStatusCode    := 0;
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || ' select t.* ';
    v_vSQL := v_vSQL || '   from DATA_INTAKE_SCORE t ';
    v_vSQL := v_vSQL || '    where t.patient_id = :PATIENT_ID ';
    v_vSQL := v_vSQL || '    and t.mid = :MID ';
    v_vSQL := v_vSQL || '    and t.intake_id = :INTAKE_ID ';
    v_vSQL := v_vSQL || '  order by t.series ';
  

    --open the cursor
    open rs for v_vSQL
      using pi_vPatientID, pi_nMID, pi_nIntakeID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;
  
/*****
 Gets recordset of all instrument score
*****/
  
  procedure GetInstrumentScoresRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                     
                                 pi_vPatientID      in varchar2,
                                 pi_nMID            in number,
                                     
                                 rs                out PCK_COMMON.refCursor,
                                 po_nStatusCode    out number,
                                 po_vStatusComment out varchar2) 
  is
  
    v_vSQL          varchar2(4000);
  
  begin
    po_nStatusCode    := 0;
    po_vStatusComment := '';

 
    v_vSQL := v_vSQL || ' select * ';
    v_vSQL := v_vSQL || '   from (select t.*, ';
    v_vSQL := v_vSQL || '                im.module, ';
    v_vSQL := v_vSQL || '                m.date_completed ';
    v_vSQL := v_vSQL || '           from data_intake_score t, '; 
    v_vSQL := v_vSQL || '                pat_pw_event_module m, '; 
    v_vSQL := v_vSQL || '                intake_module im ';
    v_vSQL := v_vSQL || '          where t.patient_id = :PATIENT_ID ';
    v_vSQL := v_vSQL || '            and t.mid = :MID ';
    v_vSQL := v_vSQL || '            and t.patient_id = m.patient_id ';
    v_vSQL := v_vSQL || '            and t.mid = m.mid ';
    v_vSQL := v_vSQL || '            and t.intake_id = m.intake_id ';
    v_vSQL := v_vSQL || '            and t.mid = im.mid(+)) a ';
    v_vSQL := v_vSQL || '  order by a.mid, a.series, date_completed, intake_id ';
      
    --open the cursor
    open rs for v_vSQL
      using pi_vPatientID, pi_nMID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

end PCK_INSTRUMENT_RESPONSES;
/

prompt
prompt Creating package body PCK_INTAKE
prompt ================================
prompt
create or replace package body tbicds.PCK_INTAKE is

/* Copyright 2015 Intellica Corporation.  

This software is protected by FAR Subpart 27.4 - Rights in Data and Copyrights and 
international treaties.  The software was produced by Intellica Corporation of 
San Antonio, Texas for the Veterans Administration (VA) under Contract Number 
VA118-14-C-0015, Project Number TAC-16-28335 and Project Title, 
'Traumatic Brain Injury Clinical Decision Support (TBI CDS) Implementation'.  
Contract dates: 8 May 2014 - 4 January 2016.  This software was finalized 
and uploaded to the VA's Open Source Electronic Health Record Alliance (OSEHRA) 
on 31 December 2015.  Unauthorized reproduction or distribution of this software 
or any portion of it may result in severe civil and criminal penalties and will 
be prosecuted to the maximum possible extent of the law.

For licensing information contact:  info@intellicacorp.com 
*/

  /*****
  Delete Instrument 
  *****/
  procedure DeleteInstrument(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP  in varchar2,
                             pi_nUserID           in number,
                                     
                             pi_vPatientID        in varchar2,
                             pi_nIntakeID         in number,
                             pi_nMID              in number,
                             pi_nPWEventModuleID  in number,
                                     
                             po_nStatusCode       out number,
                             po_vStatusComment    out varchar2)
  
   is
    v_vSQL  varchar2(4000) := '';
  
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || ' delete ';
    v_vSQL := v_vSQL || '   from data_intake d ';
    v_vSQL := v_vSQL || '  where d.patient_id = :PATIENT_ID ';
    v_vSQL := v_vSQL || '    and d.mid = :MID ';
    v_vSQL := v_vSQL || '    and d.intake_id = :INTAKE_ID ';
  
    --delete intake, cascade del will cleanup children
    execute immediate v_vSQL
    using pi_vPatientID, 
          pi_nMID, 
          pi_nIntakeID; 
    commit;
  
    --update the patient_pw_event to reset the tree leaf
    update pat_pw_event_module t 
    set  t.status = 0,
         t.date_started = null,
         t.date_completed = null,
         t.completed_by = null
    where t.patient_id = pi_vPatientID 
    and t.pw_event_module_id = pi_nPWEventModuleID;
    commit;
    
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := '';
  end;
  
/*get module type*/
procedure GetModuleType(pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        pi_nMID             in number,
                        po_nModuleType      out number,
                        po_nStatusCode      out number,
                        po_vStatusComment   out varchar2) 
  is
  
  v_nModuleType number := -1;
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    begin
      select m.module_type
        into v_nModuleType
      from tbicds.intake_module m
      where m.active=1
        and m.mid = pi_nMID;
    exception
      when others then
        v_nModuleType := -1;
    end;
                
    po_nModuleType := v_nModuleType;
    
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetModuleType(): ' || sqlErrm;
  end;
  
/*get rs of modules matching search criteria*/
procedure GetAllModuleRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2,
                            rs                  out RetRefCursor) 
  is
  
  v_vSQL varchar2(4000) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := 'select s.mid, trim(s.acronym || '' '' || s.module) as module, s.description, s.module_alt_lang, s.module_for from tbicds.intake_module s '
                || 'where s.active=1 '
                || '  and s.module_type=0 '
                || 'order by s.module asc';
                    
    open rs for v_vSQL;
    
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetAllModuleRS(): ' || sqlErrm;
  end;


/*get rs of modules that are scoreable*/
procedure GetAllScorableModuleRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2,
                            rs                  out RetRefCursor) 
  is
  
  v_vSQL varchar2(4000) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := 'select * from tbicds.intake_module s '
                || 'where s.active=1 '
                || '  and s.module_type=0 '
                || '  and s.mid in (select mid from intake_module_description where scorable =1) '
                || 'order by s.module asc';
    
    open rs for v_vSQL;
    
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetAllScorableModuleRS(): ' || sqlErrm;
  end;


/*get rs of modules matching search criteria*/
procedure GetModuleSearchRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vSearch          in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2,
                            rs                  out RetRefCursor) 
  is
  
  v_vSQL varchar2(4000) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := 'select s.mid, trim(s.acronym || '' '' || s.module) as module, s.description, s.module_alt_lang, s.module_for from tbicds.intake_module s '
                || 'where s.active=1 and s.module_type=0 and UPPER(s.acronym) || '' '' || UPPER(s.module) like :P0 '
                || 'order by s.module asc';
    
    open rs for 
    v_vSQL using UPPER('%'||pi_vSearch||'%');
   
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetModuleSearchRS(): ' || sqlErrm;
  end;

  /*US:5966
  get intake modules by group id*/
  procedure GetModuleGroupMIDRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nModuleGroupID   in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor) 
  is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    open rs for
      select t.mid, trim(t.acronym || ' ' || t.module) as module, t.description, t.module_alt_lang, t.module_for, 
             (select count(*) 
              from data_intake_score dis
              where dis.mid = t.mid) as score_count
        from intake_module t, intake_module_group_mid t2
       where t.mid = t2.mid
         and (
                   t2.module_group_id = pi_nModuleGroupID
                   or
                   pi_nModuleGroupID = -1
             )
         
       order by t2.sort_order;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetIntakeModulesRS(): ' || sqlErrm;
  end;
  
  /*US:5966
  get intake modules by group id and perform an inner search*/
  procedure GetModuleGroupMIDRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nModuleGroupID   in number,
                                pi_vSearch          in varchar2,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor) 
  is
  
  v_vSQL varchar2(4000) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := 'select t.mid, trim(t.acronym || '' '' || t.module) as module, t.description, t.module_alt_lang,' 
              || '(select count(*) from data_intake_score dis where dis.mid = t.mid) as score_count '
              || 'from intake_module t, intake_module_group_mid t2 ' 
              || 'where t.mid = t2.mid and t2.module_group_id = :P0 '
              || 'and t.active = 1 and t.module_type=0 and UPPER(t.acronym) || '' '' || UPPER(t.module) like :P1 '
              || 'order by t2.sort_order';
              
    --open recordset
    open rs for 
      v_vSQL 
    using pi_nModuleGroupID,
          UPPER('%'||pi_vSearch||'%');
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetIntakeModulesRS(): ' || sqlErrm;
  end;

  /*get module groups by group type id*/
  procedure GetModuleGroupRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_nGroupTypeID     in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor) 
  is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    if pi_nGroupTypeID != -1 then
    
      open rs for
      select *
        from intake_module_group t
       where t.module_group_type_id = pi_nGroupTypeID
       order by sort_order;
    
    else
    
       open rs for
       select -1 as MODULE_GROUP_ID,
             'All' as MODULE_GROUP_DESCR,
             1 as SORT_ORDER,
             'All' as DESCRIPTION,
             -1 as EVENT_ID,
             1 as ACTIVE,
             0 as STAT_MODALITY_ID,
             -1 as MODULE_GROUP_TYPE_ID
      from dual;
      
      end if;
              
      
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetIntakeModulesRS(): ' || sqlErrm;
  end;

  /*get module group types such as domain and clinical setting*/
  procedure GetModuleGroupTypeRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor)
  is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    open rs for
    
      select i.*
        from tbicds.intake_module_group_type i
       where i.active = 1
       order by sort_order;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetIntakeModulesRS(): ' || sqlErrm;
  end;

  /*get resposne load recordset*/
  procedure GetResponseLoadRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vLoadTable       in varchar2,
                              pi_vLoadField       in varchar2,
                              pi_vLoadFilter      in varchar2,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out RetRefCursor) 
  is
  
    strSQL long;
  
  begin
  
    strSQL            := '';
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    strSQL := strSQL || 'SELECT ' || pi_vLoadField;
    strSQL := strSQL || ' FROM ' || case
                when (lower(pi_vLoadTable) not like 'tbicds.%') then
                 'tbicds.'
              end || pi_vLoadTable;
  
    if length(pi_vLoadFilter) > 2 then
      strSQL := strSQL || ' ' || pi_vLoadFilter;
    end if;
  
    --open recordset
    open rs for strSQL;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetResponseLoadRS(): ' || sqlErrm;
  end;

  /*get intake module recordset*/
  procedure GetIntakeModulesRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor) 
  is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    open rs for
    
      select i.*
        from tbicds.intake_module i
       where i.active = 1
      --and i.module_for = 1
        and i.module_type = 0
       order by sort_order;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetIntakeModulesRS(): ' || sqlErrm;
  end;

  /*Get module group recordset*/
  procedure GetModuleGroupRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor) 
  is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    open rs for
      select *
        from tbicds.intake_module_group t
       where t.active = 1
       order by t.module_group_id;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetModuleGroupRS(): ' || sqlErrm;
  end;

  /*Get module list recordset*/
  procedure GetModulesListRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor) 
  is
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
    open rs for
      select m.module_group_id,
             m.mid,
             m.sort_order,
             m2.module,
             m2.description
        from (select imgm.*, img.module_group_descr
                from tbicds.intake_module_group_mid imgm,
                     tbicds.intake_module_group     img,
                     tbicds.intake_module           im
               where img.module_group_id = imgm.module_group_id
                 and im.mid = imgm.mid
                 and im.active = 1
                 and im.module_type = 0) m
        left join (select * from tbicds.intake_module im where im.active = 1 and im.module_type = 0) m2
          on m2.mid = m.mid
       order by m.module_group_id, m.sort_order;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetModulesListRS(): ' || sqlErrm;
  end;

  /*start the module*/
  procedure StartModule(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           
                           pi_vPatientID in varchar2,
                           pi_nMID       in number,
                           pi_nGroupID   in number,
                           pi_nIntakeID  in number,
                           
                           po_nStatusCode    out number,
                           po_vStatusComment out varchar2) 
  is
  
  v_dtSysDate date := null;
  v_nExists   number := 0;
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
    
    v_dtSysDate := sysdate;   
    
    begin
      select 1 
        into v_nExists
      from data_intake
      where patient_id = pi_vPatientID
        and intake_id = pi_nIntakeID
        and mid = pi_nMID;
    exception
      when others then
      v_nExists := 0;
    end;
    
    if v_nExists = 0 then
       --insert...    
       insert into data_intake
       (patient_id,
       intake_id,
       mid,
       start_date)
       values
       (pi_vPatientID,
       pi_nIntakeID,
       pi_nMID,
       v_dtSysDate);
       commit;
    else
      --update...
      update data_intake set
       start_date = v_dtSysDate
      where patient_id = pi_vPatientID
        and intake_id = pi_nIntakeID
        and mid = pi_nMID;
      commit;
    end if;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.StartModule(): ' || sqlErrm;
  end;
  
  /*Mark module complete*/
  procedure CompleteModule(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           
                           pi_vPatientID in varchar2,
                           pi_nMID       in number,
                           pi_nGroupID   in number,
                           pi_nIntakeID  in number,
                           
                           po_nStatusCode    out number,
                           po_vStatusComment out varchar2) 
  is
  
  v_dtSysDate date := null;
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
    
    v_dtSysDate := sysdate;   
      
    --update...
       update data_intake set
         complete = 1,
         complete_date = v_dtSysDate
       where patient_id = pi_vPatientID
         and intake_id = pi_nIntakeID
         and mid = pi_nMID;
       
    --AUDIT TRAIL
    update data_intake_responses_audit set complete_date = v_dtSysDate
    where patient_id = pi_vPatientID
      and mid = pi_nMID
      and intake_id = pi_nIntakeID
      and complete_date is null;
      
    update data_intake_score_audit set complete_date = v_dtSysDate
    where patient_id = pi_vPatientID
      and mid = pi_nMID
      and intake_id = pi_nIntakeID
      and complete_date is null;
       
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.CompleteModule(): ' || sqlErrm;
  end;


  /*Get score data as a string*/
  PROCEDURE GetScoreDataStringRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_vPatientID       in varchar2,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor)
  
   is
  
    v_vPatientID  VARCHAR2(50) := pi_vPatientID;
    v_nEncTypeID  NUMBER := 99;
    v_nMaxSeries  NUMBER := 1;
    v_nCurrSeries NUMBER := 1;
    v_nCurrMID    NUMBER := 0;
    v_dtRespDate  DATE := null;
    v_vLabel      VARCHAR2(32767) := NULL;
    v_vDATA       VARCHAR2(32767) := '';
    curEnc        RetRefCursor;
   -- CURSOR curMID IS
   --   SELECT DISTINCT mid
   --     FROM tbicds.encounter_intake_score s
   --    WHERE s.encounter_id IN
   --          (SELECT encounter_id
   --             FROM tbicds.encounter e
   --            WHERE e.patient_id = v_vPatientID
   --              AND e.encounter_type_id = v_nEncTypeID)
   --    ORDER BY mid;
  BEGIN
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    -- open the string
    v_vDATA := v_vDATA || '[';
  /*  FOR recMID IN curMID LOOP
      BEGIN
        SELECT MAX(series)
          INTO v_nMaxSeries
          FROM tbicds.encounter_intake_score
         WHERE mid = recMID.mid
           AND encounter_id IN
               (SELECT encounter_id
                  FROM tbicds.encounter e
                 WHERE e.patient_id = v_vPatientID
                   AND e.encounter_type_id = v_nEncTypeID);
      EXCEPTION
        WHEN OTHERS THEN
          v_nMaxSeries := 1;
      END;
      -- write segment: {"mid": ####, "mid_data": [
      v_vDATA := v_vDATA || '{"mid": ' || TO_CHAR(recMID.mid) ||
                 ', "mid_data": [';
      FOR n IN 1 .. v_nMaxSeries LOOP
        v_nCurrSeries := n;
        v_vDATA       := v_vDATA || '{"data": [';
        FOR recEnc IN (SELECT t1.*, t2.encounter_date
                         FROM tbicds.encounter_intake_score t1,
                              tbicds.encounter              t2
                        WHERE t2.encounter_id = t1.encounter_id
                          AND mid = recMID.mid
                          AND series = n
                          AND t2.encounter_id IN
                              (SELECT DISTINCT encounter_id
                                 FROM tbicds.encounter
                                WHERE encounter_type_id = v_nEncTypeID
                                  AND patient_id = v_vPatientID)
                        ORDER BY t2.encounter_date, t1.encounter_intake_id) LOOP
          --get the date of the assessment not the encounter
          begin
            select max(r.response_datetime)
              into v_dtRespDate
              from tbicds.encounter_intake_responses r
             where r.encounter_id = recEnc.Encounter_Id
               and r.mid = recEnc.mid
               and r.encounter_intake_id = recEnc.Encounter_Intake_Id;
          exception
            when others then
              v_dtRespDate := recEnc.Encounter_Date;
          end;
        
          --write the POINT data
          v_vDATA := v_vDATA || '["' || TO_CHAR(v_dtRespDate, 'mm/dd/yyyy') ||
                     '", "' || TO_CHAR(recEnc.score) || '"],';
          IF (recMID.mid IN (3016, 3020)) THEN
            IF recEnc.interpret IS NOT NULL THEN
              v_vLabel := recEnc.interpret;
            END IF;
          END IF;
        END LOOP;
        v_vDATA := SUBSTR(v_vDATA, 1, LENGTH(v_vDATA) - 1);
        v_vDATA := v_vDATA || ']';
        IF (v_vLabel IS NOT NULL OR LENGTH(v_vLabel) > 0) THEN
          v_vDATA  := v_vDATA || ', "label": "' || v_vLabel || '" ';
          v_vLabel := null;
        END IF;
        v_vDATA := v_vDATA || '},';
      END LOOP;
      -- close the string here
      v_vDATA := SUBSTR(v_vDATA, 1, LENGTH(v_vDATA) - 1);
      v_vDATA := v_vDATA || ']},';
    END LOOP;
    -- ******************************
    -- END OF LOOPS
    if LENGTH(v_vDATA) > 1 then
      v_vDATA := SUBSTR(v_vDATA, 1, LENGTH(v_vDATA) - 1);
    end if;
    v_vDATA := v_vDATA || ']';
    --dbms_output.put_line(v_vDATA);
  
    OPEN rs FOR
      SELECT v_vDATA AS mid_data FROM dual;*/
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.GetScoreDataStringRS(): ' || sqlErrm;
  END;
  
  /*****
  Gets next module intake_id
  *****/
  procedure GetNextMIDIntakeIDRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP   in varchar2,
                             pi_nUserID            in number,
                             pi_vPatientID          in varchar2,
                             pi_nMID                in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor) 
  is
  v_nIntakeID number;
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
    
    -- v_nIntakeID := fngetlastintakeid(pi_vPatientID, pi_nMID) + 1;
    select seqintakeid.nextval into v_nIntakeID from dual;  
  
    --open recordset
    open rs for
      select v_nIntakeID as intake_id
        from dual;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

end;
/

prompt
prompt Creating package body PCK_MILITARY
prompt ==================================
prompt
create or replace package body tbicds.PCK_MILITARY is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   /*Get military service recordset*/
   procedure GetMilitaryServiceRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
   
      --open recordset
      v_vSql := 'select * from tbicds.stat_military_service where active = 1';
      open rs for v_vSql;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_MILITARY.GetMilitaryServiceRS(): ' || sqlErrm;
   end;

   /*Get military duty station recordset*/
   procedure GetMilitaryDutyStationRS(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     po_nStatusCode      out number,
                                     po_vStatusComment   out varchar2,
                                     rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
      v_bMAJCOMRights boolean := false;
      v_bHQRights     boolean := false;
      v_nDIMS_ID      number := 0;
      v_nMAJCOM_ID    number := 0;
   begin
      po_nStatusCode    := 0;
      po_vStatusComment := '';
   
      -- get base id
      begin
         v_vSql := 'select dims_id from tbicds.app_user where fx_user_id = :P0';
         execute immediate v_vSql into v_nDIMS_ID using pi_nUserID;
      exception
         when others then
            null;
      end;
   
      --open recordset
      v_vSql := 'select distinct t.* '
                || 'from tbicds.stat_dims_base t '
                || 'where t.active = 1 '
                || 'order by t.sort_order';
      open rs for v_vSQL;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_MILITARY.GetMilitaryDutyStationRS(): ' || sqlErrm;
   end;

end;
/

prompt
prompt Creating package body PCK_NOTE
prompt ==============================
prompt
create or replace package body tbicds.PCK_NOTE is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*****
Description: Gets all cosigners for a site/region
******/
procedure GetCosignerRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vSearch                in varchar2,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is
     --var to hold like search
     v_vSearch varchar2(500) := '';

     --sql select
     v_vSQL varchar2(500) :=
      'SELECT t.*, t2.duz 
         FROM tbicds.app_user t,
              tbicds.fx_user t2
        WHERE t.fx_user_id = t2.fx_user_id 
          AND t2.region_id = :REGION_ID
          AND t2.site_id = :SITE_ID
          AND upper(t.name) 
              like upper(nvl(:SEARCH, t.name))
     ORDER BY upper(t.NAME) asc';
    
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --add % for like 
    v_vSearch := '%' || pi_vSearch || '%';
       
    --open the result set
    open rs for v_vSQL
    using pi_nregionid,
          pi_nSiteID,
          v_vSearch;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*****
Description: Gets all clinics for a site/region
******/
procedure GetClinicRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vSearch                in varchar2,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is
     --var to hold like search
     v_vSearch varchar2(500) := '';

     --sql select
     v_vSQL varchar2(500) :=
      'SELECT t.*
         FROM tbicds.utl_Clinic t
        WHERE t.region_id = :region_id
          AND t.site_id = :site_id 
          AND upper(t.clinic_label) 
              like upper(nvl(:SEARCH, t.clinic_label))
     ORDER BY upper(t.Clinic_label) asc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --add % for like 
    v_vSearch := '%' || pi_vSearch || '%';
   
    --open the result set
    open rs for v_vSQL
    using pi_nRegionID, 
          pi_nSiteID,
          v_vSearch;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
     
end;


/*****
Description: Gets all note titles for a site/region
******/
procedure GetNoteTitleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vSearch                in varchar2,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is
     --var to hold like search
     v_vSearch varchar2(500) := '';

     --sql select
     v_vSQL varchar2(500) :=
      'SELECT t.*, 
              decode(t.is_consult,1,''Y'',''N'') as consult_yn
         FROM tbicds.utl_note_title t
        WHERE t.region_id = :REGION_ID
          AND t.site_id = :SITE_ID
          AND upper(t.note_title_label) 
              like upper(nvl(:SEARCH, t.note_title_label))
     ORDER BY upper(t.note_title_label) asc';
     
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --add % for like 
    v_vSearch := '%' || pi_vSearch || '%';
    
    --open the result set
    open rs for v_vSQL
    using pi_nregionid,
          pi_nSiteID,
          v_vSearch;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Description: Gets all patient appointments for a site/region/dfn
******/
procedure GetPatientAppointmentRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      pi_dtFrom                 in date,
      pi_dtTo                   in date,
            
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*, 
              t2.clinic_label
         FROM tbicds.patient_appointment t,
              tbicds.utl_clinic t2
        WHERE t.region_id = :REGION_ID
          AND t.appt_clinic_id = t2.clinic_id
          AND t2.region_id = :REGION_ID 
          AND t2.site_id = :SITE_ID  
          AND t.site_id = :SITE_ID
          AND t.dfn = :DFN
          AND (t.appt_datetime > :FROM_DATE 
               AND t.appt_datetime < :TO_DATE)
     ORDER BY t.appt_datetime desc';
     
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs for v_vSQL
    using pi_nregionid,
          pi_nregionid,
          pi_nSiteID,
          pi_nSiteID,
          pi_vDFN,
          pi_dtFrom - 1,
          pi_dtTo + 1;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Description: Gets all patient visits for a site/region/dfn
******/
procedure GetPatientVisitRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      pi_dtFrom                 in date,
      pi_dtTo                   in date,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.* 
        FROM tbicds.patient_visit t
       WHERE region_id = :REGION_ID
         AND site_id = :SITE_ID
         AND dfn = :DFN
         AND (t.visit_datetime > :FROM_DATE 
              AND t.visit_datetime < :TO_DATE)
    ORDER BY t.visit_datetime desc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs for v_vSQL
    using pi_nregionid,
          pi_nSiteID,
          pi_vDFN,
          pi_dtFrom - 1,
          pi_dtTo + 1;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Description: Gets all patient consults for a site/region/dfn
******/
procedure GetPatientConsultRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      pi_dtFrom                 in date,
      pi_dtTo                   in date,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.* 
         FROM tbicds.patient_consult t
        WHERE region_id = :REGION_ID
          AND site_id = :SITE_ID
          AND dfn = :DFN
          AND (t.consult_datetime > :FROM_DATE 
              AND t.consult_datetime < :TO_DATE)
     ORDER BY t.consult_datetime desc';
     
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs for v_vSQL
    using pi_nregionid,
          pi_nSiteID,
          pi_vDFN,
          pi_dtFrom - 1,
          pi_dtTo + 1;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';

end;

/*****
Description: Gets all patient admissions for a site/region/dfn
******/
procedure GetPatientAdmissionRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      pi_dtFrom                 in date,
      pi_dtTo                   in date,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*
         FROM tbicds.patient_admission t 
        WHERE t.region_id = :REGION_ID 
          AND t.site_id = :SITE_ID 
          AND t.dfn = :DFN 
          AND (t.admit_datetime > :FROM_DATE 
              AND t.admit_datetime < :TO_DATE)
     ORDER BY admit_datetime desc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs for v_vSQL
    using pi_nregionid,
          pi_nSiteID,
          pi_vDFN,
          pi_dtFrom - 1,
          pi_dtTo + 1;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;




end PCK_NOTE;
/

prompt
prompt Creating package body PCK_NOTE_PREFILL
prompt ======================================
prompt
create or replace package body tbicds.PCK_NOTE_PREFILL is
/* Copyright 2015 Intellica Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

  /*get outcomes reviewed*/
  function fnGetOutcomesReviewedList(pi_vPatientID        in varchar2,
                                     pi_nPatPWEventID     in number) return varchar2
  is

    v_nBreakMID       number := -1;
    v_nBreakIntakeID  number := -1;

    v_vName           varchar2(32767) := '';
    v_vCurrentScore   varchar2(32767) := '';
    v_vPreviousScore  varchar2(32767) := '';
    v_vStatus         varchar2(32767) := '';

    v_vResponse       varchar2(32767) := '';
    po_vResponseValue varchar2(32767) := '';

  begin

    --get all outcomes that are reviewed
    for rec in (
        select
       --t.patient_id,
       --t.pat_pw_id,
       --t.pat_pw_event_id,
       --t.pw_event_module_id,
         t.mid
        ,t.intake_id
        ,t2.acronym
        ,t2.module
        ,(select es.event_status
          from pat_pw_event_entry pe,
               stat_event_status es
          where pe.event_status_id = es.event_status_id
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date =
             (select max(event_date)
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_status

        ,(select es.event_severity
          from pat_pw_event_entry pe,
               stat_event_severity es
          where pe.event_severity_id = es.event_severity_id
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date =
             (select max(event_date)
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_severity

          ,scores.description
          ,scores.interpretation
          ,scores.current_score
          ,scores.previous_score
          ,scores.exists_previous_score

          from PAT_PW_EVENT_MODULE t,
               intake_module t2,
               (select
                 t.patient_id
                ,t.mid
                ,t.intake_id
                ,t.series
                ,t.description
                ,t.interpretation
                ,t.score as current_score
                ,nvl((select 1
                  from data_intake_score s
                  where s.patient_id=t.patient_id
                    and s.mid = t.mid
                    and s.intake_id=(select max(s.intake_id)
                                     from data_intake_score s
                                     where s.patient_id = t.patient_id
                                       and s.mid = t.mid
                                       and s.intake_id < t.intake_id
                                       and s.series = t.series)
                    and s.series=t.series),0) as exists_previous_score
                ,(select s.score
                  from data_intake_score s
                  where s.patient_id=t.patient_id
                    and s.mid = t.mid
                    and s.intake_id=(select max(s.intake_id)
                                     from data_intake_score s
                                     where s.patient_id = t.patient_id
                                       and s.mid = t.mid
                                       and s.intake_id < t.intake_id
                                       and s.series = t.series)
                    and s.series=t.series) as previous_score
                from data_intake_score t
                where t.patient_id = pi_vPatientID
                  and lower(t.description) in('total score', 'total score raw', 'total score standard', 'rate')) scores
          where t.patient_id = pi_vPatientID
            and t.pat_pw_event_id = pi_nPatPWEventID
            and t2.mid = t.mid
            and nvl(t.intake_id,-1) > 0
            and t.pw_event_module_id in(select distinct pw_event_module_id
                                        from PAT_PW_EVENT_ENTRY
                                        where patient_id = pi_vPatientID
                                          and pat_pw_event_id = pi_nPatPWEventID)
            and scores.patient_id(+) = t.patient_id
            and scores.mid(+)        = t.mid
            and scores.intake_id(+)  = t.intake_id
       order by t.mid, t.date_scheduled, scores.series
       )
    loop
      -- Format string
      if v_nBreakMID = rec.mid and v_nBreakIntakeID = rec.intake_id then
        --add current score
        if rec.description is not null then
          v_vCurrentScore := v_vCurrentScore || 'Current ' || rec.description || ': ';
          if rec.current_score is null then
            v_vCurrentScore := v_vCurrentScore || '__ ' || rec.interpretation || chr(10);
          else
            v_vCurrentScore := v_vCurrentScore || rec.current_score || ' ' ||rec.interpretation || chr(10);
          end if;
        end if;
        --add previous score
        if rec.description is not null then
          if rec.exists_previous_score = 1 then
            v_vPreviousScore := v_vPreviousScore || 'Previous ' || rec.description || ': ';
            if rec.previous_score is null then
              v_vPreviousScore := v_vPreviousScore || '__ ' || rec.interpretation || chr(10);
            else
              v_vPreviousScore := v_vPreviousScore || rec.previous_score || ' ' || rec.interpretation || chr(10);
            end if;
          end if;
        end if;
      else
        -- check if we need to break...
        if v_nBreakMID != -1 or v_nBreakIntakeID != -1 then
          v_vResponse := v_vResponse || v_vName || v_vCurrentScore || v_vPreviousScore || v_vStatus;
          v_vResponse := v_vResponse || chr(10) || chr(10);

          --reset var
          v_vName := '';
          v_vCurrentScore := '';
          v_vPreviousScore := '';
          v_vStatus := '';

        end if;

        -- hold key to identify when to break
        v_nBreakMID := rec.mid;
        v_nBreakIntakeID := rec.intake_id;

        --set module name
        if rec.acronym is null then
          v_vName := rec.module || chr(10);
        else
          v_vName := rec.acronym || ' ' || rec.module || chr(10);
        end if;
        --set current score
        if rec.description is not null then
          v_vCurrentScore := 'Current ' || rec.description || ': ';
          if rec.current_score is null then
            v_vCurrentScore := v_vCurrentScore || '__ ' || rec.interpretation || chr(10);
          else
            v_vCurrentScore := v_vCurrentScore || rec.current_score || ' ' ||rec.interpretation || chr(10);
          end if;
        end if;
        --set previous score
        if rec.description is not null then
          if rec.exists_previous_score = 1 then
            v_vPreviousScore := 'Previous ' || rec.description || ': ';
            if rec.previous_score is null then
              v_vPreviousScore := v_vPreviousScore || '__ ' || rec.interpretation || chr(10);
            else
              v_vPreviousScore := v_vPreviousScore || rec.previous_score || ' ' || rec.interpretation || chr(10);
            end if;
          end if;
        end if;
        --set status
        v_vStatus := 'Status: ';
        if rec.current_status is null then
          v_vStatus := v_vStatus || '____';
        else
          v_vStatus := v_vStatus || rec.current_status;
        end if;
      end if;
    end loop;

    -- add the last one...
    v_vResponse := v_vResponse || v_vName || v_vCurrentScore || v_vPreviousScore || v_vStatus;


    if v_vResponse is null then
      v_vResponse := '______________';
    else
      v_vResponse := v_vResponse || chr(10) || chr(10);
    end if;

    po_vResponseValue := v_vResponse;
    return po_vResponseValue;

  exception
    when others then
      return po_vResponseValue;
  end;

  /*Get outcomes reviewed*/
  function fnGetOutcomesReviewedList2(pi_vPatientID        in varchar2,
                                      pi_nPatPWEventID     in number) return clob
  is

    v_nBreakMID       number := -1;
    v_nBreakIntakeID  number := -1;

    v_vName           varchar2(32767) := '';
    v_vCurrentScore   varchar2(32767) := '';
    v_vPreviousScore  varchar2(32767) := '';
    v_vStatus         varchar2(32767) := '';

    --v_vResponse       varchar2(32767) := '';
    --po_vResponseValue varchar2(32767) := '';

    v_vResponse       clob := '';
    po_vResponseValue clob := '';

  begin

    --get all outcomes that are reviewed
    for rec in (
        select
       --t.patient_id,
       --t.pat_pw_id,
       --t.pat_pw_event_id,
       --t.pw_event_module_id,
         t.mid
        ,t.intake_id
        ,t2.acronym
        ,t2.module
        ,(select es.event_status
          from pat_pw_event_entry pe,
               stat_event_status es
          where pe.event_status_id = es.event_status_id
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date =
             (select max(event_date)
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_status

        ,(select es.event_severity
          from pat_pw_event_entry pe,
               stat_event_severity es
          where pe.event_severity_id = es.event_severity_id
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date =
             (select max(event_date)
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_severity

          ,scores.description
          ,scores.interpretation
          ,scores.current_score
          ,scores.previous_score
          ,scores.exists_previous_score

          from PAT_PW_EVENT_MODULE t,
               intake_module t2,
               (select
                 t.patient_id
                ,t.mid
                ,t.intake_id
                ,t.series
                ,t.description
                ,t.interpretation
                ,t.score as current_score
                ,nvl((select 1
                  from data_intake_score s
                  where s.patient_id=t.patient_id
                    and s.mid = t.mid
                    and s.intake_id=(select max(s.intake_id)
                                     from data_intake_score s
                                     where s.patient_id = t.patient_id
                                       and s.mid = t.mid
                                       and s.intake_id < t.intake_id
                                       and s.series = t.series)
                    and s.series=t.series),0) as exists_previous_score
                ,(select s.score
                  from data_intake_score s
                  where s.patient_id=t.patient_id
                    and s.mid = t.mid
                    and s.intake_id=(select max(s.intake_id)
                                     from data_intake_score s
                                     where s.patient_id = t.patient_id
                                       and s.mid = t.mid
                                       and s.intake_id < t.intake_id
                                       and s.series = t.series)
                    and s.series=t.series) as previous_score
                from data_intake_score t
                where t.patient_id = pi_vPatientID
                  --and (
                  --  lower(t.description) in('total score', 'total score raw', 'total score standard', 'rate') or
                  --  lower(t.description) like '%subscale%'
                  --  )
                 ) scores
          where t.patient_id = pi_vPatientID
            and t.pat_pw_event_id = pi_nPatPWEventID
            and t2.mid = t.mid
            and nvl(t.intake_id,-1) > 0
            and t.pw_event_module_id in(select distinct pw_event_module_id
                                        from PAT_PW_EVENT_ENTRY
                                        where patient_id = pi_vPatientID
                                          and pat_pw_event_id = pi_nPatPWEventID)
            and scores.patient_id(+) = t.patient_id
            and scores.mid(+)        = t.mid
            and scores.intake_id(+)  = t.intake_id
       order by t.mid, t.date_scheduled, scores.series
       )
    loop
      -- Format string
      if v_nBreakMID = rec.mid and v_nBreakIntakeID = rec.intake_id then
        --add current score
        if rec.description is not null then
          v_vCurrentScore := v_vCurrentScore || 'Current ' || rec.description || ': ';
          if rec.current_score is null then
            v_vCurrentScore := v_vCurrentScore || '__ ' || rec.interpretation || chr(10);
          else
            v_vCurrentScore := v_vCurrentScore || rec.current_score || ' ' ||rec.interpretation || chr(10);
          end if;
        end if;
        --add previous score
        if rec.description is not null then
          if rec.exists_previous_score = 1 then
            v_vPreviousScore := v_vPreviousScore || 'Previous ' || rec.description || ': ';
            if rec.previous_score is null then
              v_vPreviousScore := v_vPreviousScore || '__ ' || rec.interpretation || chr(10);
            else
              v_vPreviousScore := v_vPreviousScore || rec.previous_score || ' ' || rec.interpretation || chr(10);
            end if;
          end if;
        end if;
      else
        -- check if we need to break...
        if v_nBreakMID != -1 or v_nBreakIntakeID != -1 then
          v_vResponse := v_vResponse || v_vName || v_vCurrentScore || v_vPreviousScore || v_vStatus;
          v_vResponse := v_vResponse || chr(10) || chr(10);

          --reset var
          v_vName := '';
          v_vCurrentScore := '';
          v_vPreviousScore := '';
          v_vStatus := '';

        end if;

        -- hold key to identify when to break
        v_nBreakMID := rec.mid;
        v_nBreakIntakeID := rec.intake_id;

        --set module name
        if rec.acronym is null then
          v_vName := rec.module || chr(10);
        else
          v_vName := rec.acronym || ' ' || rec.module || chr(10);
        end if;
        --set current score
        if rec.description is not null then
          v_vCurrentScore := 'Current ' || rec.description || ': ';
          if rec.current_score is null then
            v_vCurrentScore := v_vCurrentScore || '__ ' || rec.interpretation || chr(10);
          else
            v_vCurrentScore := v_vCurrentScore || rec.current_score || ' ' ||rec.interpretation || chr(10);
          end if;
        end if;
        --set previous score
        if rec.description is not null then
          if rec.exists_previous_score = 1 then
            v_vPreviousScore := 'Previous ' || rec.description || ': ';
            if rec.previous_score is null then
              v_vPreviousScore := v_vPreviousScore || '__ ' || rec.interpretation || chr(10);
            else
              v_vPreviousScore := v_vPreviousScore || rec.previous_score || ' ' || rec.interpretation || chr(10);
            end if;
          end if;
        end if;
        --set status
        v_vStatus := 'Status: ';
        if rec.current_status is null then
          v_vStatus := v_vStatus || '____';
        else
          v_vStatus := v_vStatus || rec.current_status;
        end if;
      end if;
    end loop;

    -- add the last one...
    v_vResponse := v_vResponse || v_vName || v_vCurrentScore || v_vPreviousScore || v_vStatus;


    if v_vResponse is null then
      v_vResponse := '______________';
    else
      v_vResponse := v_vResponse || chr(10) || chr(10);
    end if;

    po_vResponseValue := v_vResponse;
    return po_vResponseValue;

  exception
    when others then
      return po_vResponseValue;
  end;

  /*Get outcome notes*/
  function fnGetOutcomesNotes(pi_vPatientID              in varchar2,
                              pi_nPatPWEventID           in number) return varchar2 
  is

    v_vResponse       varchar2(32767) := '';
    po_vResponseValue varchar2(32767) := '';

  begin

    --get all outcomes notes
    for rec in (
        select
         TO_CHAR(e.event_date, 'YYYY-DD-MM HH24:MI:SS') || chr(10) || u.name || chr(10) || e.event_comment as note
        from pat_pw_event_entry e,
             app_user u
        where e.fx_user_id = u.fx_user_id
          and e.patient_id = pi_vPatientID
          and e.pat_pw_event_id = pi_nPatPWEventID
        order by e.event_date
       )
    loop
      if rec.note is not null then
          v_vResponse := v_vResponse || chr(10) || rec.note || chr(10);
      end if;
    end loop;

    if v_vResponse is null then
      v_vResponse := '______________';
    else
      v_vResponse := v_vResponse;
    end if;

    po_vResponseValue := v_vResponse;
    return po_vResponseValue;

  exception
    when others then
      return po_vResponseValue;
  end;

  /*Get question response list*/
  function fnGetQuestionResponseList(pi_vPatientID        in varchar2,
                                     pi_nModuleIdentifier in varchar2,
                                     pi_nTID              in number,
                                     pi_nQID              in number) return varchar2 
  is

    v_nIntakeID       number := -1;
    v_vResponse       varchar2(32767) := '';
    po_vResponseValue varchar2(32767) := '';

    rs RetRefCursor;
  begin

    --get the last intake id for the module specified
    begin
      select max(i.intake_id)
        into v_nIntakeID
      from data_intake i,
           intake_module m
      where i.mid = m.mid
        and i.patient_id = pi_vPatientID
        and m.identifier = pi_nModuleIdentifier;
      exception
        when others then
          v_nIntakeID := -1;
    end;

    --get all responses for the question
    for rec in (select
                  trim(
                  case
                    when r.display_type = 3 then
                      r.response || ' ' ||
                      rs.response_value ||
                      nvl(' ' || r.unit, '')
                    when r.display_type in(4,22) then
                      r.response || ' ' ||
                      rs.response_value
                    else
                      rs.response_value
                  end) as response_value
                from data_intake_responses rs,
                     intake_module m,
                     intake_response r
                where m.mid = rs.mid
                  and r.mid = rs.mid
                  and r.rid = rs.rid
                  and rs.patient_id = pi_vPatientID
                  and m.identifier = pi_nModuleIdentifier
                  and rs.tid = pi_nTID
                  and rs.qid = pi_nQID
                  and rs.intake_id = v_nIntakeID)
    loop
      if rec.response_value is not null then
        v_vResponse := v_vResponse || chr(9) || rec.response_value || chr(10);
      end if;
    end loop;

    if v_vResponse is null then
      v_vResponse := '______________';
    end if;

    po_vResponseValue := v_vResponse;
    return po_vResponseValue;

  exception
    when others then
      return po_vResponseValue;
  end;

  /*Get module responses*/
  function fnGetModuleResponses(pi_vPatientID        in varchar2,
                                pi_nModuleIdentifier in varchar2) return clob
  is
    v_nIntakeID       number := -1;
    v_nTID            number := 0;
    v_nQID            number := 0;
    v_vResponse       clob := '';
    po_vResponseValue clob := '';

    rs RetRefCursor;
  begin

    --get the last intake id for the module specified
    begin
      select max(i.intake_id)
        into v_nIntakeID
      from data_intake i,
           intake_module m
      where i.mid = m.mid
        and i.patient_id = pi_vPatientID
        and m.identifier = pi_nModuleIdentifier;
      exception
        when others then
          v_nIntakeID := -1;
    end;

    --get all question & responses for the module
    for rec in (select
                  dr.tid,
                  dr.qid,
                  REGEXP_REPLACE(iq.question, '<[^<>]+>') as question,
                  trim(REGEXP_REPLACE(
                       case
                         when ir.display_type = 3 then ir.response || ' ' || dr.response_value || nvl(' ' || ir.unit, '')
                         when ir.display_type in(4,22) then ir.response || ' ' || dr.response_value
                         else dr.response_value
                       end
                       , '<[^<>]+>')
                  ) as response
                from data_intake_responses dr,
                     intake_module im,
                     intake_topic it,
                     intake_question iq,
                     intake_response ir
                where dr.patient_id = pi_vPatientID
                  and im.identifier = pi_nModuleIdentifier
                  and dr.intake_id = v_nIntakeID

                --intake_module
                    and   dr.mid = im.mid

                --intake_topic
                    and   dr.mid = it.mid
                    and   dr.tid = it.tid

                --intake_question
                    and   dr.mid = iq.mid
                    and   dr.tid = iq.tid
                    and   dr.qid = iq.qid

                --intake_response
                    and   dr.mid = ir.mid
                    and   dr.tid = ir.tid
                    and   dr.qid = ir.qid
                    and   dr.rid = ir.rid

                order by dr.mid,
                    dr.tid,
                    dr.qid,
                    dr.rid )
    loop
      if v_nTID = 0 and v_nQID = 0 then
        v_nTID := rec.tid;
        v_nQID := rec.qid;
        if rec.question is not null then
          v_vResponse := v_vResponse || rec.question || chr(10);
        end if;
      end if;

      if v_nTID != rec.tid or v_nQID != rec.qid then
        v_nTID := rec.tid;
        v_nQID := rec.qid;
        v_vResponse := v_vResponse || chr(10);
        if rec.question is not null then
          v_vResponse := v_vResponse || rec.question || chr(10);
        end if;
      end if;

      if rec.response is not null then
        v_vResponse := v_vResponse || rec.response || chr(10);
      end if;

    end loop;

    if v_vResponse is null then
      v_vResponse := '______________';
    end if;

    po_vResponseValue := v_vResponse;
    return po_vResponseValue;

  exception
    when others then
      return po_vResponseValue;
  end;

  /*Get module responses*/
  function fnGetModuleResponses(pi_vPatientID        in varchar2,
                                pi_nModuleIdentifier in varchar2,
                                pi_nIntakeID         in number) return clob
  is
    v_nTID            number := 0;
    v_nQID            number := 0;
    v_vResponse       clob := '';
    po_vResponseValue clob := '';

    rs RetRefCursor;
  begin

    --get all question & responses for the module
    for rec in (select
                  dr.tid,
                  dr.qid,
                  dr.intake_id,
                  dr.rid,
                  dr.mid,
                  REGEXP_REPLACE(
                    REGEXP_REPLACE(
                      replace(iq.question,chr(38) || 'nbsp;',''),
                      '<br\s{0,}/{0,}>',
                      chr(10)
                    ),
                    '<[^<>]+>'
                  ) as question,
                  trim(REGEXP_REPLACE(
                       case
                         when ir.display_type = 3 then ir.response || ' ' || dr.response_value || nvl(' ' || ir.unit, '')
                         when ir.display_type in(4,22) then ir.response || ' ' || dr.response_value
                         else dr.response_value
                       end
                       , '<[^<>]+>')
                  ) as response
                from data_intake_responses dr,
                     intake_module im,
                     intake_topic it,
                     intake_question iq,
                     intake_response ir
                where dr.patient_id = pi_vPatientID
                  and im.identifier = pi_nModuleIdentifier
                  and dr.intake_id = pi_nIntakeID

                --intake_module
                    and   dr.mid = im.mid

                --intake_topic
                    and   dr.mid = it.mid
                    and   dr.tid = it.tid

                --intake_question
                    and   dr.mid = iq.mid
                    and   dr.tid = iq.tid
                    and   dr.qid = iq.qid

                --intake_response
                    and   dr.mid = ir.mid
                    and   dr.tid = ir.tid
                    and   dr.qid = ir.qid
                    and   dr.rid = ir.rid

                order by dr.mid,
                    dr.tid,
                    dr.qid,
                    dr.rid )
    loop
      if v_nTID = 0 and v_nQID = 0 then
        v_nTID := rec.tid;
        v_nQID := rec.qid;
        if rec.question is not null then
          v_vResponse := v_vResponse || rec.question || chr(10);
        end if;
      end if;

      if v_nTID != rec.tid or v_nQID != rec.qid then
        v_nTID := rec.tid;
        v_nQID := rec.qid;
        v_vResponse := v_vResponse || chr(10);
        if rec.question is not null then
          v_vResponse := v_vResponse || rec.question || chr(10);
        end if;
      end if;

      if rec.response is not null then
        --Put time in one horizontal line
        if rec.mid = 4076 and rec.tid = 1 and rec.qid = 4 and rec.rid = 125 then
           v_vResponse := v_vResponse || rec.response;
        else   
           if rec.mid = 4076 and rec.tid = 1 and rec.qid = 4 and rec.rid = 130 then
              v_vResponse := v_vResponse || REGEXP_REPLACE(rec.response,' ','');
           else
              if rec.mid = 4076 and rec.tid = 1 and rec.qid = 3 and rec.rid = 110 then
                 v_vResponse := v_vResponse || rec.response;
              else   
                 if rec.mid = 4076 and rec.tid = 1 and rec.qid = 3 and rec.rid = 115 then
                    v_vResponse := v_vResponse || REGEXP_REPLACE(rec.response,' ','');
                 else 
                    v_vResponse := v_vResponse || rec.response || chr(10);
                 end if;
              end if;   
           end if;   
        end if;
      end if;

    end loop;

    if v_vResponse is null then
      v_vResponse := '______________';
    end if;

    po_vResponseValue := v_vResponse;
    return po_vResponseValue;

  exception
    when others then
      return po_vResponseValue;
  end;

  /*Get module score*/
  function fnGetModuleScore(pi_vPatientID  in varchar2,
                            pi_nMID        in number,
                            pi_nIntakeID   in number) return clob
  is

    v_nCtr            number := 0;
    v_vResponse       clob := '';
    po_vResponseValue clob := '';

    rs RetRefCursor;
  begin

    --get all scores for the module
    for rec in (select
                 t.series,
                 t.offSet1,
                 t.offSet2,
                 rpad(t.description,t.offSet1 + 2) || lpad(t.score,t.offSet2) || '  ' || t.interpretation as ScoreLine
                from (
                  select
                    series,
                    description,
                    score,
                    interpretation,
                    case
                      when (select max(length(off1.description)) from data_intake_score off1 where off1.patient_id = pi_vPatientID and off1.mid = pi_nMID and off1.intake_id = pi_nIntakeID) <= 11 then 11
                      else (select max(length(off1.description)) from data_intake_score off1 where off1.patient_id = pi_vPatientID and off1.mid = pi_nMID and off1.intake_id = pi_nIntakeID)
                    end as offSet1,
                    case
                      when (select max(length(off2.score)) from data_intake_score off2 where off2.patient_id = pi_vPatientID and off2.mid = pi_nMID and off2.intake_id = pi_nIntakeID) <= 5 then 5
                      else (select max(length(off2.score)) from data_intake_score off2 where off2.patient_id = pi_vPatientID and off2.mid = pi_nMID and off2.intake_id = pi_nIntakeID)
                    end as offSet2
                  from data_intake_score s
                  where patient_id = pi_vPatientID
                    and mid = pi_nMID
                    and intake_id = pi_nIntakeID
                ) t
                order by t.series
                )
    loop
      v_nCtr := v_nCtr + 1;

      if v_nCtr = 1 then
        v_vResponse := rpad('Description',rec.offset1 + 2) || lpad('Score',rec.offset2) || '  ' || 'Interpretation' || chr(10);
      end if;

/*      if rec.description is not null then
        v_vResponse := v_vResponse || rpad(rec.description, rec.offset1 + 2);
      end if;

      if rec.score is not null then
        v_vResponse := v_vResponse || lpad(rec.score, rec.offset2) || '  ';
      end if;

      if rec.interpretation is not null then
        v_vResponse := v_vResponse || rec.interpretation;
      end if;
  */
      v_vResponse := v_vResponse || rec.Scoreline;

      v_vResponse := v_vResponse || chr(10);

    end loop;

    if v_vResponse is null then
      v_vResponse := '______________';
    end if;

    po_vResponseValue := v_vResponse;
    return po_vResponseValue;

  exception
    when others then
      return po_vResponseValue;
  end;

  /*Get all completed modules*/
  function fnGetAllCompletedModules(pi_vPatientID  in varchar2,
                                    pi_nPatPWEventID in number) return clob
  is

    v_nCtr            number := 0;
    v_vResponse       clob := '';
    po_vResponseValue clob := '';

    rs RetRefCursor;

  begin

      for rec in (select
                   m.module as ModuleSection,
                   PCK_NOTE_PREFILL.fnGetModuleScore(em.patient_id, em.mid, em.intake_id) as ScoreSection,
                   PCK_NOTE_PREFILL.fnGetModuleResponses(em.patient_id, m.identifier,em.intake_id) as QASection
                  from pat_pw_event_module em,
                       intake_module m
                  where m.mid = em.mid
                    and em.patient_id = pi_vPatientID
                    and em.pat_pw_event_id = pi_nPatPWEventID
                    and em.status = 1
                    and case
                          when em.mid = 4042 then
                            case
                              when (select c.rid from data_intake_responses c where c.intake_id = em.intake_id and c.tid=1 and qid=1) != 21 then 1
                              else 0
                            end
                          else 1
                        end = 1)
      loop
        if rec.modulesection is not null then
          v_vResponse := v_vResponse || rec.modulesection || chr(10);
          v_vResponse := v_vResponse || '------------------------------------------------------------------------' || chr(10);
        end if;

        if rec.scoresection is not null and rec.scoresection != '______________' then
          v_vResponse := v_vResponse || rec.scoresection || chr(10);
        end if;

        if rec.qasection is not null and rec.qasection != '______________' then
          v_vResponse := v_vResponse || 'Questions & Responses' || chr(10);
          v_vResponse := v_vResponse || rec.qasection || chr(10) || chr(10);
        end if;

      end loop;

      if v_vResponse is null then
        v_vResponse := '______________';
      end if;

      po_vResponseValue := v_vResponse;
      return po_vResponseValue;

 exception
    when others then
      return po_vResponseValue;
  end;


end PCK_NOTE_PREFILL;
/

prompt
prompt Creating package body PCK_PATIENT
prompt =================================
prompt
create or replace package body tbicds.PCK_PATIENT is

  /* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  /*
  gets basic patient demographic data given the patients fx_user_id
  */
  procedure GetPatientIDRS(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_vKey             in varchar2,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out RetRefCursor) 
  is
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    open rs for
      select t.PATIENT_ID,
             tbicds.fnc_utl_decstr(t.FIRST_NAME, pi_vKey, t.PATIENT_ID) as first_name,
             tbicds.fnc_utl_decstr(t.MI, pi_vKey, t.PATIENT_ID) as mi,
             tbicds.fnc_utl_decstr(t.LAST_NAME, pi_vKey, t.PATIENT_ID) as last_name,
             tbicds.fnc_utl_decstr(t.SSN, pi_vKey, t.PATIENT_ID) as ssn,
             mid(tbicds.fnc_utl_decstr(t.last_name, pi_vKey, t.PATIENT_ID),
                 1,
                 1) ||
             mid(tbicds.fnc_utl_decstr(t.ssn, pi_vKey, t.PATIENT_ID), 6, 9) as LNSSNLAST4,
             tbicds.fnc_utl_decstr(t.GENDER, pi_vKey, t.PATIENT_ID) as gender,
             t.MARITAL_STATUS_ID,
             to_date(tbicds.fnc_utl_decstr(t.dob, pi_vKey, t.PATIENT_ID),
                     'MM/DD/YYYY') as dob,
             t.EDUCATION_LEVEL_ID,
             t.PROVIDER_ID,
             t.ADDRESS1,
             t.ADDRESS2,
             t.CITY,
             t.POSTAL_CODE,
             t.HOMEPHONE,
             t.CELLPHONE,
             t.WORKPHONE,
             tbicds.fnc_utl_decstr(t.EMAIL, pi_vKey, t.PATIENT_ID) as email,
             t.STATE_ID,
             t.FX_USER_ID,
             t.LAST_UPDATED,
             t.LAST_UPDATED_BY,
             t.PORTAL_USER_ID,
             t.WRK_PHONE_CALL,
             t.HOME_PHONE_CALL,
             t.HOME_PHONE_MSG,
             t.CELL_PHONE_CALL,
             t.EMAIL_MSG,
             trunc(months_between(SYSDATE,
                                  to_date(tbicds.fnc_utl_decstr(t.dob,
                                                                pi_vKey,
                                                                t.PATIENT_ID),
                                          'MM/DD/YYYY')) / 12) as patient_age
        from tbicds.patient_demographics t
       where t.fx_user_id = pi_nUserID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_PATIENT.GetPatientIDRS(): ' || sqlErrm;
  end;

  /*
  gets dataset to populate Patient Portal Lookup List
  */
  procedure GetPatientPortalListRS(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vKey             in varchar2,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2,
                                   rs                  out Pck_Utl_Common.refCursor) 
  is
  begin
  
    --default status to ok
    po_nStatusCode    := Pck_Utl_Common.c_nResultStatus_Success;
    po_vStatusComment := null;
  
    open rs for
      select t.patient_id,
             tbicds.fnc_utl_decstr(t.first_name, pi_vKey, t.patient_id) as first_name,
             tbicds.fnc_utl_decstr(t.mi, pi_vKey, t.patient_id) as mi,
             tbicds.fnc_utl_decstr(t.last_name, pi_vKey, t.patient_id) as last_name,
             tbicds.fnc_utl_decstr(t.last_name, pi_vKey, t.patient_id) || ', ' ||
             tbicds.fnc_utl_decstr(t.first_name, pi_vKey, t.patient_id) || ' ' ||
             tbicds.fnc_utl_decstr(t.mi, pi_vKey, t.patient_id) as name,
             t.homephone as phone,
             tbicds.fnc_utl_decstr(t.email, pi_vKey, t.patient_id) as email,
             t.fx_user_id,
             t2.user_name,
             t2.is_locked,
             t2.is_inactive
        from tbicds.patient_demographics t, tbicds.fx_user t2
       where t.fx_user_id = t2.fx_user_id
         and t.provider_id in
             (select provider_id
                from tbicds.app_user s
               where s.dims_id in
                     (select dims_id
                        from tbicds.app_user
                       where fx_user_id = pi_nUserID))
       order by tbicds.fnc_utl_decstr(t.last_name, pi_vKey, t.patient_id),
                tbicds.fnc_utl_decstr(t.first_name, pi_vKey, t.patient_id);
  
  exception
    when others then
    
      po_nStatusCode    := Pck_Utl_Common.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PATIENT.GetPatientPortalListDS(): ' ||
                           sqlCode || ': ' || sqlErrm;
    
  end;

  /*
   Updates patient demographics data from the demographics page in the application 
   */
  procedure UpdatePatientDemographics(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      pi_vKey             in varchar2,
                                      pi_vPatientID       in varchar2,
                                      pi_vFirstName       in varchar2,
                                      pi_vMI              in varchar2,
                                      pi_vLastName        in varchar2,
                                      pi_vSponsorSSN      in varchar2,
                                      pi_vSSN             in varchar2,
                                      pi_vGender          in varchar2,
                                      pi_vDateOfBirth     in varchar2,
                                      pi_vProviderID      in varchar2,
                                      pi_vAddress1        in varchar2,
                                      pi_vAddress2        in varchar2,
                                      pi_vCity            in varchar2,
                                      pi_vPostal_Code     in varchar2,
                                      pi_vHomePhone       in varchar2,
                                      pi_vCellPhone       in varchar2,
                                      pi_vWorkPhone       in varchar2,
                                      pi_vEmail           in varchar2,
                                      pi_vStateID         in varchar2,
                                      pi_nCellPhoneMsg    in number,
                                      pi_nEmailMsg        in number,
                                      pi_nCallPreference  in number,
                                      pi_nPrefLangID      in number,
                                      pi_vPrefLangOther   in varchar2,
                                      pi_nDutyStatusID    in number,
                                      pi_nHandPrefID      in number,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2) 
  is
  
    v_nMAJCOM_ID number := 0;
    v_vPMDSQL    long := '';
  
    v_vDOB      varchar2(50) := '';
    v_nCallPref number := null;
  
    v_nHomeCall number := 0;
    v_nCellCall number := 0;
    v_nWorkCall number := 0;
  
    v_nPrefLangID   number := null;
    v_nDutyStatusID number := null;
    v_nHandPrefID   number := null;
  
    v_vProviderID varchar2(50) := null;
  
  begin
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    if pi_nCallPreference > 0 then
      if bitand(pi_nCallPreference, 1) > 0 then
        v_nHomeCall := 1;
      end if;
    
      if bitand(pi_nCallPreference, 2) > 0 then
        v_nCellCall := 1;
      end if;
    
      if bitand(pi_nCallPreference, 4) > 0 then
        v_nWorkCall := 1;
      end if;
    end if;
  
    if pi_nPrefLangID > 0 then
      v_nPrefLangID := pi_nPrefLangID;
    end if;
  
    if pi_nDutyStatusID > 0 then
      v_nDutyStatusID := pi_nDutyStatusID;
    end if;
  
    if pi_nHandPrefID > 0 then
      v_nHandPrefID := pi_nHandPrefID;
    end if;
  
    if pi_vDateOfBirth != '-1' then
      v_vDOB := pi_vDateOfBirth;
    end if;
  
    --get provider id
    begin
      select provider_id
        into v_vProviderID
        from app_user t
       where t.fx_user_id = pi_nUserID;
    exception
      when others then
        v_vProviderID := null;
    end;
  
    update tbicds.patient_demographics
       set first_name      = tbicds.fnc_utl_encstr(upper(pi_vFirstName),
                                                   pi_vKey,
                                                   upper(pi_vPatientID)),
           mi              = tbicds.fnc_utl_encstr(upper(pi_vMI),
                                                   pi_vKey,
                                                   upper(pi_vPatientID)),
           last_name       = tbicds.fnc_utl_encstr(upper(pi_vLastName),
                                                   pi_vKey,
                                                   upper(pi_vPatientID)),
           ssn             = tbicds.fnc_utl_encstr(pi_vSSN,
                                                   pi_vKey,
                                                   upper(pi_vPatientID)),
           gender          = tbicds.fnc_utl_encstr(pi_vGender,
                                                   pi_vKey,
                                                   upper(pi_vPatientID)),
           dob             = tbicds.fnc_utl_encstr(v_vDOB,
                                                   pi_vKey,
                                                   upper(pi_vPatientID)),
           provider_id     = pi_vProviderID,
           address1        = pi_vAddress1,
           address2        = pi_vAddress2,
           city            = upper(pi_vCity),
           postal_code     = pi_vPostal_Code,
           homephone       = pi_vHomePhone,
           cellphone       = pi_vCellPhone,
           workphone       = pi_vWorkPhone,
           email           = tbicds.fnc_utl_encstr(pi_vEmail,
                                                   pi_vKey,
                                                   upper(pi_vPatientID)),
           wrk_phone_call  = pi_nCallPreference,
           home_phone_call = pi_nCallPreference,
           cell_phone_call = pi_nCallPreference,
           home_phone_msg  = pi_nCellPhoneMsg,
           email_msg       = pi_nEmailMsg,
           state_id        = pi_vStateID,
           
           preferred_language_id    = v_nPrefLangID,
           preferred_language_other = pi_vPrefLangOther,
           duty_status_id           = v_nDutyStatusID,
           hand_preference_id       = v_nHandPrefID,
           
           last_updated    = sysdate,
           last_updated_by = pi_nUserID
     where patient_id = pi_vPatientID;
    commit;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_PATIENT.UpdatePatientDemographics(): ' ||
                           sqlErrm;
  end;

  /*get a record set of patients back that match criteria*/
  procedure GetPatientLookupRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vKey             in varchar2,
                               pi_nSelectedCases   in number,
                               pi_nSearchType      in number,
                               pi_vSearchValue     in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor) 
  is
  
    v_const_search_last_name number := 1;
    v_const_search_fmp_ssn   number := 3;
   
    strSQL       varchar2(4000);
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    strSQL := 'select ';
    strSQL := strSQL || ' p.PATIENT_ID, ';
  
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.FIRST_NAME, 
              :pi_vKey, p.PATIENT_ID) as first_name, ';
  
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.MI, 
              :pi_vKey, p.PATIENT_ID) as mi, ';
  
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.LAST_NAME, 
              :pi_vKey, p.PATIENT_ID) as last_name, ';
  
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.SSN,
              :pi_vKey, p.PATIENT_ID) as ssn, ';
  
    strSQL := strSQL || ' mid(tbicds.fnc_utl_decstr(p.last_name, 
              :pi_vKey, p.PATIENT_ID), 1, 1) || 
              mid(tbicds.fnc_utl_decstr(p.ssn, 
              :pi_vKey, p.PATIENT_ID), 6, 9) as LNSSNLAST4, ';
  
    strSQL := strSQL || ' mid(tbicds.fnc_utl_decstr(p.last_name, ''' ||
              pi_vKey ||
              ''', p.PATIENT_ID), 1, 1) || mid(tbicds.fnc_utl_decstr(p.ssn, ''' ||
              pi_vKey || ''', p.PATIENT_ID), 6, 9) as fmpssnlast4, ';
  
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.GENDER, ''' || pi_vKey ||
              ''', p.PATIENT_ID) as gender, ';
  
    strSQL := strSQL || ' p.MARITAL_STATUS_ID, ';
  
    strSQL := strSQL || ' to_date(tbicds.fnc_utl_decstr(p.dob, ''' ||
              pi_vKey || ''', p.PATIENT_ID), ''MM/DD/YYYY'') as dob, ';
  
    strSQL := strSQL || ' to_char(to_date(tbicds.fnc_utl_decstr(p.dob, ''' ||
              pi_vKey ||
              ''', p.PATIENT_ID), ''MM/DD/YYYY''), ''MM/DD/YYYY'') as birthdate, ';
  
    strSQL := strSQL || ' p.EDUCATION_LEVEL_ID, ';
    strSQL := strSQL || ' p.PROVIDER_ID, ';
    strSQL := strSQL || ' p.ADDRESS1, ';
    strSQL := strSQL || ' p.ADDRESS2, ';
    strSQL := strSQL || ' p.CITY, ';
    strSQL := strSQL || ' p.POSTAL_CODE, ';
    strSQL := strSQL || ' p.HOMEPHONE, ';
    strSQL := strSQL || ' p.CELLPHONE, ';
    strSQL := strSQL || ' p.WORKPHONE, ';
    
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.EMAIL, 
           :pi_vKey, p.PATIENT_ID) as email, ';
    
    strSQL := strSQL || ' p.STATE_ID, ';
    strSQL := strSQL || ' p.FX_USER_ID, ';
    strSQL := strSQL || ' p.LAST_UPDATED, ';
    strSQL := strSQL || ' p.LAST_UPDATED_BY, ';
    strSQL := strSQL || ' p.PORTAL_USER_ID, ';
    strSQL := strSQL || ' p.WRK_PHONE_CALL, ';
    strSQL := strSQL || ' p.HOME_PHONE_CALL, ';
    strSQL := strSQL || ' p.HOME_PHONE_MSG, ';
    strSQL := strSQL || ' p.CELL_PHONE_CALL, ';
    strSQL := strSQL || ' p.EMAIL_MSG, ';
    
    strSQL := strSQL || ' trunc(months_between(SYSDATE, 
           to_date(tbicds.fnc_utl_decstr(p.dob, 
           :pi_vKey, p.PATIENT_ID), ''MM/DD/YYYY'')) / 12) as patient_age, ';
    
    strSQL := strSQL || ' 0 as case_closed ';
    
    strSQL := strSQL || ' from tbicds.patient_demographics p ';
  
    strSQL := strSQL || ' where ';
    
    strSQL := strSQL || ' p.site_id in (';
    
    strSQL := strSQL || 'select site_id ';
    strSQL := strSQL || '  from tbicds.fx_user s ';
    strSQL := strSQL || ' where fx_user_id = :pi_nUserID ) ';
  
    -- is the search by last name?
    if pi_nSearchType = v_const_search_last_name then
  
      strSQL := strSQL || ' and UPPER(';
      
      strSQL := strSQL || 'tbicds.fnc_utl_decstr(p.LAST_NAME, 
                :pi_vKey, p.PATIENT_ID)';
                
      strSQL := strSQL || ') like UPPER(''' || pi_vSearchValue || ''')';
      strSQL := strSQL || ' order by p.last_name, p.first_name asc';
   
    --is the search by lastname initial SS last 4
    elsif pi_nSearchType = v_const_search_fmp_ssn then
  
      strSQL := strSQL || ' and ';
    
      strSQL := strSQL || ' mid(tbicds.fnc_utl_decstr(p.last_name,
                :pi_vKey, p.PATIENT_ID), 1, 1) || 
                mid(tbicds.fnc_utl_decstr(p.ssn, 
                :pi_vKey, p.PATIENT_ID), 6, 9) ';
      strSQL := strSQL || ' = :pi_vSearchValue ';
      strSQL := strSQL || ' order by p.last_name, p.first_name asc';
      
    end if;
  
    if pi_nSearchType = v_const_search_last_name then
  
      open rs for strSQL 
      using pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_nUserID,
            --last name search binds
            pi_vKey;
     
     end if;
    
    if pi_nSearchType = v_const_search_fmp_ssn then
    
      open rs for strSQL 
      using pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_vKey,
            pi_nUserID,
            --LSSN search binds
            pi_vKey,
            pi_vKey,
            pi_vSearchValue;           
    
    end if;
    
         
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_PATIENT.getPatientLookupRS(): ' || sqlErrm;
  end;


  /* Returns the patient demographics recordset  */
  procedure GetPatientDemographicsRS(pi_vSessionID       in varchar2,
                                     pi_vSessionClientIP in varchar2,
                                     pi_nUserID          in number,
                                     pi_vKey             in varchar2,
                                     pi_vPatientID       in varchar2,
                                     po_nStatusCode      out number,
                                     po_vStatusComment   out varchar2,
                                     rs                  out RetRefCursor) 
  is
    --v_nTreatmentID number;
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
    --v_nTreatmentID    := 0;
  
   -- select max(treatment_id)
   --   into v_nTreatmentID
   --   from treatment
   --  where patient_id = pi_vPatientID;
  
    open rs for
      select t.PATIENT_ID,
             t.DFN,
             tbicds.fnc_utl_decstr(t.FIRST_NAME, pi_vKey, t.PATIENT_ID) as first_name,
             tbicds.fnc_utl_decstr(t.MI, pi_vKey, t.PATIENT_ID) as mi,
             tbicds.fnc_utl_decstr(t.LAST_NAME, pi_vKey, t.PATIENT_ID) as last_name,
             tbicds.fnc_utl_decstr(t.SSN, pi_vKey, t.PATIENT_ID) as ssn,
             mid(tbicds.fnc_utl_decstr(t.last_name, pi_vKey, t.PATIENT_ID),
                 1,
                 1) ||
             mid(tbicds.fnc_utl_decstr(t.ssn, pi_vKey, t.PATIENT_ID), 6, 9) as LNSSNLAST4,
             tbicds.fnc_utl_decstr(t.GENDER, pi_vKey, t.PATIENT_ID) as gender,
             t.MARITAL_STATUS_ID,
             to_date(tbicds.fnc_utl_decstr(t.dob, pi_vKey, t.PATIENT_ID),
                     'MM/DD/YYYY') as dob,
             t.EDUCATION_LEVEL_ID,
             t.PROVIDER_ID,
             t.ADDRESS1,
             t.ADDRESS2,
             t.CITY,
             t.POSTAL_CODE,
             t.HOMEPHONE,
             t.CELLPHONE,
             t.WORKPHONE,
             tbicds.fnc_utl_decstr(t.EMAIL, pi_vKey, t.PATIENT_ID) as email,
             t.STATE_ID,
             t.FX_USER_ID,
             t.LAST_UPDATED,
             t.LAST_UPDATED_BY,
             t.PORTAL_USER_ID,
             t.WRK_PHONE_CALL,
             t.HOME_PHONE_CALL,
             t.HOME_PHONE_MSG,
             t.CELL_PHONE_CALL,
             t.EMAIL_MSG,
             
             (select s.name
                from tbicds.app_user s
               where s.provider_id = t.PROVIDER_ID) as provider_name,
             trunc(months_between(SYSDATE,
                                  to_date(fnc_utl_decstr(t.dob,
                                                         pi_vKey,
                                                         t.PATIENT_ID),
                                          'MM/DD/YYYY')) / 12) as patient_age,
             '' as MILITARY_STATUS_TITLE,
             '' as MILITARY_SERVICE_TITLE,
             '' as MARITAL_STATUS_TITLE,
             '' as GRADE,
             tbicds.fnc_utl_decstr(t.gender, pi_vKey, pi_vPatientID) as GENDER_DESC,
             '' as BASE,
             0 as referral_count,
             0 as OPENCASE_COUNT,             
             t.wrk_phone_call,
             t.home_phone_call,
             t.home_phone_msg,
             t.email_msg,
             t.preferred_language_id,
             t.preferred_language_other,
             /*tbicds.fnc_utl_decstr(t.preferred_language_other,
                                   pi_vKey,
                                   t.PATIENT_ID) as preferred_language_other,*/
             duty_status_id,
             hand_preference_id
      
        from tbicds.patient_demographics    t
       where t.patient_id = pi_vPatientID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_PATIENT.GetPatientDemographicsRS(): ' ||
                           sqlErrm;
  end;

  /*
  Insert patient demographics
  */
  procedure InsertPatientDemographics(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      --Patient Table
                                      pi_vKey            in varchar2,
                                      pi_vPatientID      in varchar2,
                                      pi_vEncounterID    in varchar2,
                                      pi_vFirstName      in varchar2,
                                      pi_vMI             in varchar2,
                                      pi_vLastName       in varchar2,
                                      pi_vSponsorSSN     in varchar2,
                                      pi_vSSN            in varchar2,
                                      pi_vGender         in varchar2,
                                      pi_vDateOfBirth    in varchar2,
                                      pi_vProviderID     in varchar2,
                                      pi_vAddress1       in varchar2,
                                      pi_vAddress2       in varchar2,
                                      pi_vCity           in varchar2,
                                      pi_vPostal_Code    in varchar2,
                                      pi_vHomePhone      in varchar2,
                                      pi_vCellPhone      in varchar2,
                                      pi_vWorkPhone      in varchar2,
                                      pi_vEmail          in varchar2,
                                      pi_vStateID        in varchar2,
                                      pi_nCellPhoneMsg   in number,
                                      pi_nEmailMsg       in number,
                                      pi_nCallPreference in number,
                                      po_nStatusCode     out number,
                                      po_vStatusComment  out varchar2)
  is
  
    v_nRelationshipID number;
    v_nSSNCount       number;
    v_vDOB            varchar2(50) := '';
    v_nCallPref       number := null;
  
    v_nHomeCall number := 0;
    v_nCellCall number := 0;
    v_nWorkCall number := 0;
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_nRelationshipID := 0;
    v_nSSNCount       := 0;
  
    if pi_nCallPreference > 0 then
      if bitand(pi_nCallPreference, 1) > 0 then
        v_nHomeCall := 1;
      end if;
    
      if bitand(pi_nCallPreference, 2) > 0 then
        v_nCellCall := 1;
      end if;
    
      if bitand(pi_nCallPreference, 4) > 0 then
        v_nWorkCall := 1;
      end if;
    end if;
  
    --SSN Check For Duplicate
    select count(ssn)
      into v_nSSNCount
      from tbicds.patient_demographics t
     where tbicds.fnc_utl_decstr(t.SSN, pi_vKey, t.PATIENT_ID) = pi_vSSN;
  
    if (v_nSSNCount > 0) then
      po_nStatusCode    := Pck_Common.c_nResultStatus_Error;
      po_vStatusComment := po_vStatusComment ||
                           'Social Security Number already exists. ';
    end if;
  
    -- return if error
    if po_nStatusCode = Pck_Common.c_nResultStatus_Error then
      po_vStatusComment := 'Error: ' || rtrim(po_vStatusComment, ', ');
      return;
    end if;
  
    if pi_vDateOfBirth != '-1' then
      v_vDOB := pi_vDateOfBirth;
    end if;
  
    insert into tbicds.patient_demographics t
      (patient_id,
       first_name,
       mi,
       last_name,
       ssn,
       gender,
       dob,
       provider_id,
       address1,
       address2,
       city,
       postal_code,
       homephone,
       cellphone,
       workphone,
       email,
       state_id,
       home_phone_call,
       cell_phone_call,
       wrk_phone_call,
       home_phone_msg,
       email_msg,
       last_updated,
       last_updated_by)
    values
      (upper(pi_vPatientID),
       tbicds.fnc_utl_encstr(upper(pi_vFirstName),
                             pi_vKey,
                             upper(pi_vPatientID)),
       tbicds.fnc_utl_encstr(upper(pi_vMI), pi_vKey, upper(pi_vPatientID)),
       tbicds.fnc_utl_encstr(upper(pi_vLastName),
                             pi_vKey,
                             upper(pi_vPatientID)),
       tbicds.fnc_utl_encstr(pi_vSSN, pi_vKey, upper(pi_vPatientID)),
       tbicds.fnc_utl_encstr(pi_vGender, pi_vKey, upper(pi_vPatientID)),
       tbicds.fnc_utl_encstr(v_vDOB, pi_vKey, upper(pi_vPatientID)),
       pi_vProviderID,
       pi_vAddress1,
       pi_vAddress2,
       upper(pi_vCity),
       pi_vPostal_Code,
       pi_vHomePhone,
       pi_vCellPhone,
       pi_vWorkPhone,
       tbicds.fnc_utl_encstr(pi_vEmail, pi_vKey, upper(pi_vPatientID)),
       pi_vStateID,
       v_nHomeCall,
       v_nCellCall,
       v_nWorkCall,
       pi_nCellPhoneMsg,
       pi_nEmailMsg,
       sysdate,
       pi_nUserID);
    commit;
  
    --Create Initial Patient Sponsor Record Needed By Assessments --Assessments can only to Updates
    /*insert into tbicds.patient_sponsor
      (patient_id, relationship_id, last_updated, last_updated_by)
    values
      (pi_vPatientID, v_nRelationshipID, sysdate, pi_nUserID);
    commit;*/
  
    --Create Initial Emergency Contact Record Needed By Assessments --Assessments can only to Updates
    /*insert into tbicds.patient_emergency_contact
      (patient_id, relationship_id, last_updated, last_updated_by)
    values
      (pi_vPatientID, v_nRelationshipID, sysdate, pi_nUserID);
    commit;*/
  
  --  insert into tbicds.treatment
  --    (treatment_id,
  --     patient_id,
  --     initial_visit_date,
  --     last_updated,
  --     last_updated_by)
  --  values
  --    (1, pi_vPatientID, sysdate, sysdate, pi_nUserID);
  --  commit;
  
    --REVAMP 20130219 DS: As requested by VA (Dr Kuna), do not create a default encounter
    --
    --insert into tbicds.encounter
    --   (encounter_id,
    --    treatment_id,
    --    patient_id,
    --    encounter_date,
    --    last_updated,
    --    last_updated_by)
    -- values
    --   (pi_vEncounterID, 1, pi_vPatientID, sysdate, sysdate, pi_nUserID);
    -- commit;
    --
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_PATIENT.InsertPatientDemographics(): ' ||
                           sqlErrm;
    
  end;

  /*
  does the patient only have 1 encounte for the latest treatment
  */
  procedure InitialEncounter(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vPatientID       in varchar2,
                             po_nInitialEnc      out number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2) 
  is
  
    v_nCount       number;
    v_nTreatmentID number;
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
    v_nCount          := 0;
    v_nTreatmentID    := 0;
    po_nInitialEnc    := 0;
  
    --get the number of encounters for the
    --current open treatment
 --   select count(*)
 --     into v_nCount
 --     from tbicds.encounter e
 --    where e.patient_id = pi_vPatientID
 --      and e.encounter_type_id in (0, 6, 8)
 --      and e.treatment_id =
 --          (select max(treatment_id)
 --             from tbicds.treatment t
 --            where t.patient_id = pi_vPatientID
 --              and nvl(t.case_closed, 0) = 0);
  
    if (v_nCount = 1) then
      po_nInitialEnc := 1;
    end if;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_INTAKE.InitialEncounter(): ' || sqlErrm;
  end;

  /*
  Get patient treatment id recordset
  */
  procedure GetPatientTreatmentIdRS(pi_vSessionID       in varchar2,
                                    pi_vSessionClientIP in varchar2,
                                    pi_nUserID          in number,
                                    pi_vPatientID       in varchar2,
                                    po_nStatusCode      out number,
                                    po_vStatusComment   out varchar2,
                                    rs                  out RetRefCursor)
  is
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    --open recordset
--    open rs for
--      select treatment_id
--        from tbicds.treatment t
--       where patient_id = pi_vPatientID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_PATIENT.GetPatientTreatmentIdRS(): ' ||
                           sqlErrm;
  end;

  /*
  Remove patient intake assessments
  */
  procedure DelIncPatIntakeAssessments(pi_vSessionID       in varchar2,
                                       pi_vSessionClientIP in varchar2,
                                       pi_nUserID          in number,
                                       pi_vPatientID       in varchar2,
                                       po_nStatusCode      out number,
                                       po_vStatusComment   out varchar2)
  is
    v_nNumOfIncAssessments number := 0;
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
   /* for rec in ( -- select all INCOMPLETE encounter intakes for module for patient
                select ei.*
                  from tbicds.encounter_intake ei
                 where ei.encounter_id in
                       ( -- select all encounters for patient
                        select e.encounter_id
                          from tbicds.encounter e
                         where e.patient_id = pi_vPatientID))
    
     loop
      begin
      
        v_nNumOfIncAssessments := 0;
      
        --select all encounter intakes responses for module for encounter by mid
        select count(eir.encounter_id)
          into v_nNumOfIncAssessments
          from tbicds.encounter_intake_responses eir
         where eir.encounter_id = rec.encounter_id
           and eir.mid = rec.mid;
      
        if v_nNumOfIncAssessments = 0 then
        
          delete from tbicds.encounter_intake ei
           where ei.encounter_id = rec.encounter_id
             and ei.encounter_intake_id = rec.encounter_intake_id
             and ei.mid = rec.mid;
        
          commit;
        
        end if;
      
      exception
        when others then
          rollback;
      end;
    end loop;*/
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_PATIENT.DelIncPatIntakeAssessments(): ' ||
                           sqlErrm;
  end;

  /*
  get incomplete patient assessments
  */
  procedure IncPatIntakeAssessments(pi_vSessionID            in varchar2,
                                    pi_vSessionClientIP      in varchar2,
                                    pi_nUserID               in number,
                                    pi_vPatientID            in varchar2,
                                    po_nHasIncPatAssessments out number,
                                    po_nStatusCode           out number,
                                    po_vStatusComment        out varchar2) 
  is
  
    v_nNumOfIncAssessments number := 0;
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
   /* for rec in ( -- select all INCOMPLETE encounter intakes for module for patient
                select ei.*
                  from tbicds.encounter_intake ei
                 where ei.encounter_id in
                       ( -- select all encounters for patient
                        select e.encounter_id
                          from tbicds.encounter e
                         where e.patient_id = pi_vPatientID))
    
     loop
      begin
      
        v_nNumOfIncAssessments := 0;
      
        --select all encounter intakes responses for module for encounter by mid
        select count(eir.encounter_id)
          into v_nNumOfIncAssessments
          from tbicds.encounter_intake_responses eir
         where eir.encounter_id = rec.encounter_id
           and eir.mid = rec.mid;
      
        if v_nNumOfIncAssessments = 0 then
          po_nHasIncPatAssessments := 1;
        end if;
      
      exception
        when others then
          rollback;
      end;
    end loop;
  */
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_PATIENT.IncPatIntakeAssessments(): ' ||
                           sqlErrm;
  end;


  /*
  delete patient assigned modules
  */
  procedure DeletePatientAssignedModule(pi_vPatientID     in varchar2,
                                        nMID              in number,
                                        po_nStatusCode    out number,
                                        po_vStatusComment out varchar2)
   is
    v_vSQL constant varchar2(32767) := 'delete from tbicds.patient_module where patient_id = :pi_vPatientID 
                                                                   and mid = :nMID 
                                                                   and status = 0
                                                                   and date_completed is null';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    execute immediate v_vSQL
      using pi_vPatientID, nMID;
    commit;
  
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PATIENT.DeletePatientAssignedModule(): ' ||
                           sqlErrm;
  end;

  /*
  Update patient user rights
  */
  procedure updatePatFxUserRights
   is
    curPat pck_common.refCursor;
    recPat tbicds.patient_demographics%rowtype;
  
  begin
  
    open curPat for
      select p.*
        from tbicds.patient_demographics p
       where p.fx_user_id is not null
         and p.fx_user_id not in
             (select fx_user_id from tbicds.fx_user_rights);
  
    loop
      fetch curPat
        into recPat;
      exit when curPat%notfound;
    
      insert into tbicds.fx_user_rights
        (fx_user_id, user_rights, read_only, user_type)
      values
        (recPat.Fx_User_Id, 0, 0, 0);
      commit;
    
    end loop;
    close curPat;
  
  end;

  /*
  Returns patient socioeconomics recordset 
  */
  procedure GetPatientSocioeconomicsRS(pi_vSessionID       in varchar2,
                                       pi_vSessionClientIP in varchar2,
                                       pi_nUserID          in number,
                                       pi_vKey             in varchar2,
                                       pi_vPatientID       in varchar2,
                                       po_nStatusCode      out number,
                                       po_vStatusComment   out varchar2,
                                       rs                  out RetRefCursor)
  is
  begin
    po_nStatusCode    := 0;
    po_vStatusComment := '';
    open rs for
      select patient_id,
             highest_grade_id,
             highest_degree_id,
             marital_status_id,
             employment_status_id,
             job_classification_id,
             last_modified,
             last_modified_by,
             tbicds.fnc_utl_decstr(t.employment_status_other,
                                   pi_vKey,
                                   t.patient_id)
        from patient_socioeconomic t
       where t.patient_id = pi_vPatientID;
  
  exception
    when others then
      po_nStatusCode    := -1;
      po_vStatusComment := 'PCK_PATIENT.GetPatientSocioeconomicsRS(): ' ||
                           sqlCode || ': ' || sqlErrm;
  end;

  /*
  Updates patient socioeconomics data 
  */
  procedure UpdatePatientSocioeconomics(pi_vSessionID             in varchar2,
                                        pi_vSessionClientIP       in varchar2,
                                        pi_nUserID                in number,
                                        pi_vKey                   in varchar2,
                                        pi_vPatientID             in varchar2,
                                        pi_nHighestGradeID        in number,
                                        pi_nHighestDegreeID       in number,
                                        pi_nMaritalStatusID       in number,
                                        pi_nEmploymentStatusID    in number,
                                        pi_nJobClassificationID   in number,
                                        pi_vEmploymentStatusOther in varchar2,
                                        po_nStatusCode            out number,
                                        po_vStatusComment         out varchar2)
  is
  
    v_nHighestGradeID        number := null;
    v_nHighestDegreeID       number := null;
    v_nMaritalStatusID       number := null;
    v_nEmploymentStatusID    number := null;
    v_nJobClassificationID   number := null;
    v_vEmploymentStatusOther varchar2(255) := null;
  
    v_nCount number := 0;
  
  begin
    po_nStatusCode    := 0;
    po_vStatusComment := '';
  
    --check if the patient record exists
    begin
      select count(*)
        into v_nCount
        from patient_socioeconomic t
       where t.patient_id = pi_vPatientID;
    exception
      when others then
        v_nCount := 0;
    end;
  
    if v_nCount < 1 then
      --insert record
      InsertPatientSocioeconomics(pi_vSessionID             => pi_vSessionID,
                                  pi_vSessionClientIP       => pi_vSessionClientIP,
                                  pi_nUserID                => pi_nUserID,
                                  pi_vKey                   => pi_vKey,
                                  pi_vPatientID             => pi_vPatientID,
                                  pi_nHighestGradeID        => pi_nHighestGradeID,
                                  pi_nHighestDegreeID       => pi_nHighestDegreeID,
                                  pi_nMaritalStatusID       => pi_nMaritalStatusID,
                                  pi_nEmploymentStatusID    => pi_nEmploymentStatusID,
                                  pi_nJobClassificationID   => pi_nJobClassificationID,
                                  pi_vEmploymentStatusOther => pi_vEmploymentStatusOther,
                                  po_nStatusCode            => po_nStatusCode,
                                  po_vStatusComment         => po_vStatusComment);
      return;
    end if;
  
    if pi_nHighestGradeID > 0 then
      v_nHighestGradeID := pi_nHighestGradeID;
    end if;
  
    if pi_nHighestDegreeID > 0 then
      v_nHighestDegreeID := pi_nHighestDegreeID;
    end if;
  
    if pi_nMaritalStatusID > 0 then
      v_nMaritalStatusID := pi_nMaritalStatusID;
    end if;
  
    if pi_nEmploymentStatusID > 0 then
      v_nEmploymentStatusID := pi_nEmploymentStatusID;
    end if;
  
    if pi_nJobClassificationID > 0 then
      v_nJobClassificationID := pi_nJobClassificationID;
    end if;
  
    if length(pi_vEmploymentStatusOther) > 0 then
      v_vEmploymentStatusOther := pi_vEmploymentStatusOther;
    end if;
  
    update patient_socioeconomic t
       set t.highest_grade_id        = v_nHighestGradeID,
           t.highest_degree_id       = v_nHighestDegreeID,
           t.marital_status_id       = v_nMaritalStatusID,
           t.employment_status_id    = v_nEmploymentStatusID,
           t.job_classification_id   = v_nJobClassificationID,
           t.employment_status_other = v_vEmploymentStatusOther,
           t.last_modified           = sysdate,
           t.last_modified_by        = pi_nUserID
     where t.patient_id = pi_vPatientID;
  
    commit;
  
  exception
    when others then
      po_nStatusCode    := -1;
      po_vStatusComment := 'PCK_PATIENT.UpdatePatientSocioeconomics(): ' ||
                           sqlCode || ': ' || sqlErrm;
  end;

  /*
  Inserts patient socioeconomics data 
  */
  procedure InsertPatientSocioeconomics(pi_vSessionID             in varchar2,
                                        pi_vSessionClientIP       in varchar2,
                                        pi_nUserID                in number,
                                        pi_vKey                   in varchar2,
                                        pi_vPatientID             in varchar2,
                                        pi_nHighestGradeID        in number,
                                        pi_nHighestDegreeID       in number,
                                        pi_nMaritalStatusID       in number,
                                        pi_nEmploymentStatusID    in number,
                                        pi_nJobClassificationID   in number,
                                        pi_vEmploymentStatusOther in varchar2,
                                        po_nStatusCode            out number,
                                        po_vStatusComment         out varchar2)
  is
  
    v_nHighestGradeID        number := null;
    v_nHighestDegreeID       number := null;
    v_nMaritalStatusID       number := null;
    v_nEmploymentStatusID    number := null;
    v_nJobClassificationID   number := null;
    v_vEmploymentStatusOther varchar2(255) := null;
  
  begin
    po_nStatusCode    := 0;
    po_vStatusComment := '';
  
    if pi_nHighestGradeID > 0 then
      v_nHighestGradeID := pi_nHighestGradeID;
    end if;
  
    if pi_nHighestDegreeID > 0 then
      v_nHighestDegreeID := pi_nHighestDegreeID;
    end if;
  
    if pi_nMaritalStatusID > 0 then
      v_nMaritalStatusID := pi_nMaritalStatusID;
    end if;
  
    if pi_nEmploymentStatusID > 0 then
      v_nEmploymentStatusID := pi_nEmploymentStatusID;
    end if;
  
    if pi_nJobClassificationID > 0 then
      v_nJobClassificationID := pi_nJobClassificationID;
    end if;
  
    if length(pi_vEmploymentStatusOther) > 0 then
      v_vEmploymentStatusOther := pi_vEmploymentStatusOther;
    end if;
  
    insert into patient_socioeconomic
      (patient_id,
       highest_grade_id,
       highest_degree_id,
       marital_status_id,
       employment_status_id,
       job_classification_id,
       last_modified,
       last_modified_by,
       employment_status_other)
    values
      (pi_vPatientID,
       v_nHighestDegreeID,
       v_nHighestDegreeID,
       v_nMaritalStatusID,
       v_nEmploymentStatusID,
       v_nJobClassificationID,
       sysdate,
       pi_nUserID,
       v_vEmploymentStatusOther);
  
    commit;
  
  exception
    when others then
      po_nStatusCode    := -1;
      po_vStatusComment := 'PCK_PATIENT.InsertPatientSocioeconomics(): ' ||
                           sqlCode || ': ' || sqlErrm;
  end;

end;
/

prompt
prompt Creating package body PCK_PATIENT_TX_STEP
prompt =========================================
prompt
create or replace package body tbicds.PCK_PATIENT_TX_STEP is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*
Insert patient step
*/
   procedure InsertPatientStep(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              
                              pi_vPatientID in varchar2,
                              pi_nStep      in number,
                              
                              po_nStatusCode    out number,
                              po_vStatusComment out varchar2)
   is
      v_vSql                               varchar2(4000);
      v_nProfile                number := 1;
      v_nStartedBaseline        number := 2;
      v_nBaselineQuestionnaires number := 4;
      v_nStartedVideos          number := 8;
      v_nVideos                 number := 16;
      v_nCPAPData               number := 32;
      v_nStep number := 0;
      v_nCount       number;
      v_nRecCount    number := 0;
      v_nCurrentStep number := 0;
   begin
      v_vSql := 'select count(*) from tbicds.patient_treatment_step where patient_id = :P0';
      execute immediate v_vSql into v_nRecCount using pi_vPatientID;
   
      if v_nRecCount > 0 then
         v_vSql := 'select treatment_step from tbicds.patient_treatment_step where patient_id = :P0';
         execute immediate v_vSql into v_nCurrentStep using pi_vPatientID;
      end if;
   
      if (bitand(v_nCurrentStep, v_nProfile) = 0) then
         -- set step value for complete patient profile (from the portal)
         -- only if this step was not set before
         if (bitand(pi_nStep, v_nProfile) = v_nProfile) then
            v_nStep := v_nStep + v_nProfile;
         end if;
      elsif (bitand(v_nCurrentStep, v_nProfile) = v_nProfile) then
         v_nStep := v_nStep + v_nProfile;
      end if;
   
      --insert step other than PROFILE
      if (bitand(pi_nStep, v_nProfile) = 0) then
         v_nStep := v_nStep + pi_nStep;
      end if;
   
      --check status of Baseline questionnaires
      v_nCount := 0;
      v_vSql := 'select count(*) '
                || 'from tbicds.patient_module t '
                || 'where t.patient_id = :P0 '
                || 'and (t.module_group_id = 2 and t.status = 1) ';
      execute immediate v_vSql into v_nCount using pi_vPatientID;
   
      if v_nCount > 0 then
         v_nStep := v_nStep + v_nStartedBaseline;
      end if;
   
      v_nCount := 0;
      v_vSql := 'select count(*) '
                || 'from tbicds.patient_event t '
                || 'where t.patient_id = :P0 '
                || 'and (t.status = 1 and t.event_id = 5) ';
      execute immediate v_vSql into v_nCount using pi_vPatientID;
   
      if v_nCount > 0 then
         v_nStep := v_nStep + v_nBaselineQuestionnaires;
      end if;
   
      --check status of video events
      v_nCount := 0;
      v_vSql := 'select count(*) '
                || 'from tbicds.patient_event t '
                || 'where t.patient_id = :P0 '
                || 'and (t.status = 1 and t.event_id in (3, 4)) ';
      execute immediate v_vSql into v_nCount using pi_vPatientID;
      
      if v_nCount = 1 then
         v_nStep := v_nStep + v_nStartedVideos;
      elsif v_nCount = 2 then
         v_nStep := v_nStep + v_nStartedVideos + v_nVideos;
      end if;
   
      --check status of CPAP Data
      v_nCount := 0;
      v_vSql := 'select count(*) from tbicds.patient_cpap t where t.patient_id = :P0 ';
      execute immediate v_vSql into v_nCount using pi_vPatientID;
      
      if v_nCount > 0 then
         v_nStep := v_nStep + v_nCPAPData;
      end if;
   
      --insert or update
      if v_nRecCount > 0 then
         v_vSql := 'update tbicds.patient_treatment_step t '
                   || 'set t.treatment_step = :P0 '
                   || 'where t.patient_id = :P1 ';
         execute immediate v_vSql using v_nStep, pi_vPatientID;
      else
         v_vSql := 'insert into tbicds.patient_treatment_step (patient_id, treatment_step) '
                   || 'values (:P0, :P1) ';
         execute immediate v_vSql using pi_vPatientID, v_nStep;
      end if;
      commit;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_PATIENT_TX_STEP.InsertPatientStep(): ' || sqlErrm;
   end;

   /*
   Update patient steps
   */
   procedure UpdatePatientSteps(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vPatientID in varchar2,
                               po_nStatusCode    out number,
                               po_vStatusComment out varchar2)
   is
      v_vSql                               varchar2(4000);
      v_nProfile                number := 1;
      v_nStartedBaseline        number := 2;
      v_nBaselineQuestionnaires number := 4;
      v_nStartedVideos          number := 8;
      v_nVideos                 number := 16;
      v_nCPAPData               number := 32;
      v_nStep number := 0;
      v_nCount       number;
      v_nRecCount    number := 0;
      v_nCurrentStep number := 0;
   begin
      v_vSql := 'select count(*) from tbicds.patient_treatment_step where patient_id = :P0';
      execute immediate v_vSql into v_nRecCount using pi_vPatientID;
   
      if v_nRecCount > 0 then
         v_vSql := 'select treatment_step from tbicds.patient_treatment_step where patient_id = :P0';
         execute immediate v_vSql into v_nCurrentStep using pi_vPatientID;
      end if;
   
      if (bitand(v_nCurrentStep, v_nProfile) = v_nProfile) then
         v_nStep := v_nStep + v_nProfile;
      end if;
   
      --check status of Baseline questionnaires
      v_nCount := 0;
      v_vSql := 'select count(*) '
                || 'from tbicds.patient_module '
                || 'where patient_id = :P0 '
                || 'and (module_group_id = 2 and status = 1) ';
      execute immediate v_vSql into v_nCount using pi_vPatientID;
   
      if v_nCount > 0 then
         v_nStep := v_nStep + v_nStartedBaseline;
      end if;
   
      v_nCount := 0;
      v_vSql := 'select count(*) '
                || 'from tbicds.patient_event t '
                || 'where t.patient_id = :P0 '
                || 'and (t.status = 1 and t.event_id = 5) ';
      execute immediate v_vSql into v_nCount using pi_vPatientID;
   
      if v_nCount > 0 then
         v_nStep := v_nStep + v_nBaselineQuestionnaires;
      end if;
   
      --check status of video events
      v_nCount := 0;
      v_vSql := 'select count(*) '
                || 'from tbicds.patient_event t '
                || 'where t.patient_id = :P0 '
                || 'and (t.status = 1 and t.event_id in (3, 4)) ';
      execute immediate v_vSql into v_nCount using pi_vPatientID;

      if v_nCount = 1 then
         v_nStep := v_nStep + v_nStartedVideos;
      elsif v_nCount = 2 then
         v_nStep := v_nStep + v_nStartedVideos + v_nVideos;
      end if;
   
      --check status of CPAP Data
      v_nCount := 0;
      v_vSql := 'select count(*) from tbicds.patient_cpap t where t.patient_id = :P0 ';
      execute immediate v_vSql into v_nCount using pi_vPatientID;
   
      if v_nCount > 0 then
         v_nStep := v_nStep + v_nCPAPData;
      end if;
   
      --insert or update
      if v_nRecCount > 0 then
         v_vSql := 'update tbicds.patient_treatment_step t '
                   || 'set t.treatment_step = :P0 '
                   || 'where t.patient_id = :P1 ';
         execute immediate v_vSql using v_nStep, pi_vPatientID;
      else
         v_vSql := 'insert into tbicds.patient_treatment_step (patient_id, treatment_step) '
                   || 'values (:P0, :P1) ';
         execute immediate v_vSql using pi_vPatientID, v_nStep;
      end if;
      commit;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_PATIENT_TX_STEP.UpdatePatientSteps(): ' || sqlErrm;
   end;

   /*
   remove patient step
   */
   procedure DeletePatientStep(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vPatientID in varchar2,
                              pi_nStep      in number,
                              po_nStatusCode    out number,
                              po_vStatusComment out varchar2)
   is
      v_vSql                               varchar2(4000);
      v_nStep        number;
      v_nRecCount    number := 0;
      v_nCurrentStep number := 0;
   begin
      v_vSql := 'select count(*) from tbicds.patient_treatment_step where patient_id = :P0';
      execute immediate v_vSql into v_nRecCount using pi_vPatientID;
   
      if v_nRecCount > 0 then
         v_vSql := 'select treatment_step from tbicds.patient_treatment_step where patient_id = :P0';
         execute immediate v_vSql into v_nCurrentStep using pi_vPatientID;
      
         if (bitand(v_nCurrentStep, pi_nStep) = pi_nStep) then
            v_nStep := v_nCurrentStep - pi_nStep;
         end if;
         
         v_vSql := 'update tbicds.patient_treatment_step set treatment_step = :P0 where patient_id = :P1';
         execute immediate v_vSql using v_nStep, pi_vPatientID;
         commit;
      end if;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_PATIENT_TX_STEP.DeletePatientStep(): ' || sqlErrm;
   end;

   /*
   Get patient step recordset
   */
   procedure GetPatientStepRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vPatientID in varchar2,
                             po_nStatusCode    out number,
                             po_vStatusComment out varchar2,
                             rs                out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      v_vSql := 'select nvl(t.treatment_step, 0) as step, '
                || 'nvl(t.notification_step, 0) as notification_step '
                || 'from tbicds.patient_treatment_step t '
                || 'where t.patient_id = :P0 ';
      open rs for v_vSql using pi_vPatientID;
   
   exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_PATIENT_TX_STEP.GetPatientStepRS(): ' || sqlErrm;
   end;

   /*
   Update notification step
   */
   procedure UpdateNotificationStep(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID        in varchar2,
                                   pi_nNotificationStep in number,
                                   po_nStatusCode    out number,
                                   po_vStatusComment out varchar2)
   is
      v_vSql                               varchar2(4000);
      v_nNotificationStep number := 0;
   begin
      v_vSql := 'select notification_step from tbicds.patient_treatment_step where patient_id = :P0';
      execute immediate v_vSql into v_nNotificationStep using pi_vPatientID;
   
      if bitand(v_nNotificationStep, pi_nNotificationStep) = 0 then
         v_nNotificationStep := v_nNotificationStep + pi_nNotificationStep;
         
         v_vSql := 'update tbicds.patient_treatment_step set notification_step = :P0 where patient_id = :P1';
         execute immediate v_vSql using v_nNotificationStep, pi_vPatientID;
         commit;
      end if;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_PATIENT_TX_STEP.UpdateNotificationStep(): ' || sqlErrm;
   end;

end;
/

prompt
prompt Creating package body PCK_PAT_ETHNICITY_RACE
prompt ============================================
prompt
create or replace package body tbicds.PCK_PAT_ETHNICITY_RACE is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  /*
  insert patient ethnicity
  */
  procedure InsertPatientEthnicity(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID       in varchar2,
                                   pi_nEthnicityID     in number,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2) 
  is
    v_vSQL constant varchar2(32767) := 'insert into tbicds.patient_ethnicity
       (patient_id,
        ethnicity_id)
        values
       (:PatientID,
        :EthnicityID)';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    execute immediate v_vSQL
      using pi_vPatientID, pi_nEthnicityID;
    commit;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.InsertPatientEthnicity(): ' ||
                           sqlErrm;
  end;

  /*
  insert patient race
  */
  procedure InsertPatientRace(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vPatientID       in varchar2,
                              pi_nRaceID          in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2)
  is
    v_vSQL constant varchar2(32767) := 'insert into tbicds.patient_race
       (patient_id,
        race_id)
        values
       (:PatientID,
        :RaceID)';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    execute immediate v_vSQL
      using pi_vPatientID, pi_nRaceID;
    commit;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.InsertPatientRace(): ' ||
                           sqlErrm;
  end;

  /*
  Insert patient ethnicity race source
  */
  procedure InsertPatEthRaceSource(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID       in varchar2,
                                   pi_nSourceID        in number,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2)
  is
    v_vSQL constant varchar2(32767) := 'insert into tbicds.pat_eth_race_source
       (patient_id,
        eth_race_source_id)
        values
       (:PatientID,
        :EthRaceSourceID)';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    execute immediate v_vSQL
      using pi_vPatientID, pi_nSourceID;
    commit;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.InsertPatEthRaceSource(): ' ||
                           sqlErrm;
  end;

  /*
  Get ethnicity recordset
  */
  procedure GetEthnicityRS(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out RetRefCursor)
  is
    v_vSQL varchar2(32767) := 'select t.*
       from tbicds.stat_ethnicity t
       order by t.sort_order';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    open rs for v_vSQL;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.GetEthnicityRS(): ' ||
                           sqlErrm;
  end;

  /*
  Get race recordset
  */
  procedure GetRaceRS(pi_vSessionID       in varchar2,
                      pi_vSessionClientIP in varchar2,
                      pi_nUserID          in number,
                      po_nStatusCode      out number,
                      po_vStatusComment   out varchar2,
                      rs                  out RetRefCursor)
  is
    v_vSQL varchar2(32767) := 'select t.*
       from tbicds.stat_race t
       order by t.sort_order';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    open rs for v_vSQL;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.GetRaceRS(): ' ||
                           sqlErrm;
  end;

  /*
  Get ethnicity race source recordset
  */
  procedure GetEthRaceSourceRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor)
  is
    v_vSQL varchar2(32767) := 'select t.*
       from tbicds.stat_eth_race_source t';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    open rs for v_vSQL;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.GetEthRaceSourceRS(): ' ||
                           sqlErrm;
  end;

  /*
  Returns patient ethnicity recordset 
  */
  procedure GetPatientEthnicityRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  pi_vPatientID       in varchar2,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor)
  is
    v_vSQL varchar2(32767) := 'select p.*, 
                                      c.item
                                 from tbicds.patient_ethnicity p, 
                                      tbicds.stat_data_collection c
                                where p.patient_id = :PATIENT_ID
                                  and c.collection_type = ''_ETHNICITY''
                                  and p.ethnicity_id = c.collection_item_id(+)';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    open rs for v_vSQL
      using pi_vPatientID;
      
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.GetPatientEthnicityRS(): ' ||
                           sqlErrm;
  end;

  /*
  Returns patient race recordset 
  */
  procedure GetPatientRaceRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vPatientID       in varchar2,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor)
  is
    v_vSQL varchar2(32767) := 'select race_id from patient_race where patient_id= :PatientID';
    
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    open rs for v_vSQL
      using pi_vPatientID;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.GetPatientRaceRS(): ' ||
                           sqlErrm;
  end;

  /*
  Get patient race lsit as a string
  */
  function GetPatientRaceListString(pi_vPatientID in varchar2) return varchar2
    is
       
    v_vSQL varchar(32767) := 'select t.item as race_title
       from stat_data_collection t
       where t.collection_type = ''_RACE''
         and t.collection_item_id in(select race_id from patient_race where patient_id= :PatientID)
         and t.active = 1
       order by t.collection_item_id';
  
    curPatientRaces pck_common.refCursor;
  
    v_vRace varchar2(32767) := '';
  
    v_vRaceList varchar2(32767) := '';
  begin
    open curPatientRaces for v_vSQL
      using pi_vPatientID;
  
    fetch curPatientRaces
      into v_vRace;
  
    v_vRaceList := v_vRace;
  
    loop
    
      fetch curPatientRaces
        into v_vRace;
      exit when not curPatientRaces%found;
    
      v_vRaceList := v_vRaceList || ', ' || v_vRace;
    
    end loop;
  
    return replace(v_vRaceList, ', ' || v_vRace, ' and ' || v_vRace);
  exception
    when others then
      return null;
  end;

  /*
  Get patient ethnicity race source recordset
  */
  procedure GetPatEthRaceSourceRS(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  pi_vPatientID       in varchar2,
                                  po_nStatusCode      out number,
                                  po_vStatusComment   out varchar2,
                                  rs                  out RetRefCursor)
  is
    v_vSQL varchar2(32767) := 'select p.*, s.eth_race_source_name
       from tbicds.pat_eth_race_source p, tbicds.stat_eth_race_source s
       where p.patient_id = :PatientID
       and p.eth_race_source_id = s.eth_race_source_id';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    open rs for v_vSQL
      using pi_vPatientID;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.GetPatientRaceRS(): ' ||
                           sqlErrm;
  end;

  /*
  Remove patient ethnicity
  */
  procedure DeletePatientEthnicity(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID       in varchar2,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2)
   is
    v_vSQL constant varchar2(32767) := 'delete from tbicds.patient_ethnicity p
       where p.patient_id = :PatientID';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    execute immediate v_vSQL
      using pi_vPatientID;
    commit;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.DeletePatientEthnicity(): ' ||
                           sqlErrm;
  end;

  /*
  Remove patient race
  */
  procedure DeletePatientRace(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              pi_vPatientID       in varchar2,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2)
  is
    v_vSQL constant varchar2(32767) := 'delete from tbicds.patient_race p
       where p.patient_id = :PatientID';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    execute immediate v_vSQL
      using pi_vPatientID;
    commit;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.DeletePatientRace(): ' ||
                           sqlErrm;
  end;

  /*
  Remove patient ethnicity race source
  */
  procedure DeletePatEthRaceSource(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID       in varchar2,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2)
  is
    v_vSQL constant varchar2(32767) := 'delete from tbicds.pat_eth_race_source p
       where p.patient_id = :PatientID';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    execute immediate v_vSQL
      using pi_vPatientID;
    commit;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.DeletePatEthRaceSource(): ' ||
                           sqlErrm;
  end;

  /*
  Updates patient race selected values 
  */  
  procedure UpdatePatientRace(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              
                              pi_vPatientID in varchar2,
                              pi_vValues    in varchar2,
                              
                              po_nStatusCode    out number,
                              po_vStatusComment out varchar2)
  is
  
    v_vRecDelim   varchar2(1) := ',';
    v_vColDelim   varchar2(1) := ';';
    v_nRecPos     number := 0;
    v_nColPos     number := 0;
    v_nPrevRecPos number := 0;
    v_nPrevColPos number := 0;
    v_vRecord     varchar2(32767) := '';
    v_vColumn     varchar2(32767) := '';
    v_nColIndex   number := 0;
  
    --
    v_vValue varchar2(4000);
  
  begin
  
    po_nStatusCode    := 0;
    po_vStatusComment := '';
  
    if ((pi_vValues is null) or (LENGTH(pi_vValues) < 1)) then
      return;
    else
      delete from patient_race t where t.patient_id = pi_vPatientID;
    end if;
  
    --split records
    loop
      v_nRecPos := INSTR(pi_vValues, v_vRecDelim, v_nRecPos + 1);
      exit when v_nRecPos = 0;
      v_vRecord     := substr(pi_vValues,
                              v_nPrevRecPos + 1,
                              v_nRecPos - v_nPrevRecPos - 1);
      v_nPrevRecPos := v_nRecPos;
    
      --split columns from record
      --v_nColPos     := 0;
      --v_nPrevColPos := 0;
      --v_vColumn     := '';
      --v_nColIndex   := 0;
    
      --loop
      --  v_nColPos := INSTR(v_vRecord, v_vColDelim, v_nColPos + 1);
      --  exit when v_nColPos = 0;
      --  v_vColumn     := substr(v_vRecord,
      --                          v_nPrevColPos + 1,
      --                          v_nColPos - v_nPrevColPos - 1);
      --  v_nPrevColPos := v_nColPos;
    
      --  --loop columns
      --  if v_nColIndex = 0 then
      --    v_vValue := v_vColumn;
      --  end if;
    
      --  v_nColIndex := v_nColIndex + 1;
      --end loop;
    
      --do something here
      insert into patient_race
        (patient_id, race_id)
      values
        (pi_vPatientID, to_number(v_vRecord));
    
    end loop;
  
    commit;
  
  exception
    when others then
    
      po_nStatusCode    := 1;
      po_vStatusComment := '';
    
  end;

  /*
  Updates patient ethnicity 
  */ 
  procedure UpdatePatientEthnicity(pi_vSessionID       in varchar2,
                                   pi_vSessionClientIP in varchar2,
                                   pi_nUserID          in number,
                                   pi_vPatientID       in varchar2,
                                   pi_nEthnicityID     in number,
                                   po_nStatusCode      out number,
                                   po_vStatusComment   out varchar2)
  is
    v_vSQL constant varchar2(32767) := 'insert into tbicds.patient_ethnicity
       (patient_id,
        ethnicity_id)
        values
       (:PatientID,
        :EthnicityID)';
  
    v_vSQL2 constant varchar2(32767) := 'delete from tbicds.patient_ethnicity t
        where t.patient_id = :PatientID';
  begin
    po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
    po_vStatusComment := '';
  
    execute immediate v_vSQL2
      using pi_vPatientID;
  
    execute immediate v_vSQL
      using pi_vPatientID, pi_nEthnicityID;
    commit;
  exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Error;
      po_vStatusComment := 'PCK_PAT_ETHNICITY_RACE.UpdatePatientEthnicity(): ' ||
                           sqlErrm;
  end;

end;
/

prompt
prompt Creating package body PCK_PAT_TREATMENT
prompt =======================================
prompt
create or replace package body tbicds.PCK_PAT_TREATMENT is

/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*delete a treatment program*/
procedure DeleteTreatmentProgram( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                                
                           pi_nRegionID            in number,
                           pi_nSiteID              in number,
                           pi_vPatientID           in varchar2,
                           pi_nProgramID          in number,
                          
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          )
is
    v_nPatTreatmentID number := 0;
   
begin
  
    po_nStatusCode    := 0;
    po_vStatusComment := '';
   
    delete from tbicds.pat_treatment_program t 
    where t.program_id = pi_nProgramID;
    commit;


exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*delete a treatment*/
procedure DeleteTreatment( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                                
                           pi_nRegionID            in number,
                           pi_nSiteID              in number,
                           pi_vPatientID           in varchar2,
                           pi_nTreatmentID         in number,
                          
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          )
is
    v_nPatTreatmentID number := 0;
   
begin
  
    po_nStatusCode    := 0;
    po_vStatusComment := '';
   
    delete from tbicds.pat_treatment_program t 
    where t.treatment_id = pi_nTreatmentID;
    commit;
    
    delete from tbicds.pat_treatment t 
    where t.treatment_id = pi_nTreatmentID;
    commit;


exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*update patient treatment program record*/
procedure UpdateTreatmentProgram( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                           pi_vPatientID           in varchar2,
                           pi_nTreatmentID         in number,
                           pi_nProgramID           in number,
                           
                           pi_nCPAID               in number, 
                           pi_dtInitialDate        in date,
                           pi_dtEndDate            in date,
                                
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          )
is
    v_nPatTreatmentID number := 0;
    
    v_vSQL long :=

        'update tbicds.pat_treatment_program
         set  INITIAL_DATE = :INITIAL_DATE,
              END_DATE = :END_DATE,
              CPA_ID = :CPA_ID
        where TREATMENT_ID = :TREATMENT_ID
          and PROGRAM_ID = :PROGRAM_ID 
          and PATIENT_ID = :PATEINT_ID
          ';
begin
  
    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    
    --execute the SQL
    execute immediate v_vSQL
    using pi_dtInitialDate,
          pi_dtEndDate,
          pi_nCPAID, 
          pi_nTreatmentID,
          pi_nProgramID,
          pi_vPatientID;  
           
    commit;


exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*update patient treatment record*/
procedure UpdateTreatment( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                           pi_vPatientID           in varchar2,
                           pi_nTreatmentID         in number,
                           
                           pi_nTreatmentType       in number, 
                           pi_vTreatmentTitle      in varchar2,
                           
                           pi_dtInitialDate        in date,
                           pi_dtEndDate            in date,
                                
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          )
is
    v_nPatTreatmentID number := 0;
    
    v_vSQL long :=

        'update tbicds.pat_treatment
         set  INITIAL_DATE = :INITIAL_DATE,
              END_DATE = :END_DATE,
              TREATMENT_TYPE_ID = :TREAT_TYPE,
              TREATMENT_TITLE = :TREAT_TITLE
        where TREATMENT_ID = :TREATMENT_ID
          and PATIENT_ID = :PATEINT_ID
          ';
begin
  
    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    
    --execute the SQL
    execute immediate v_vSQL
    using pi_dtInitialDate,
          pi_dtEndDate,
          pi_nTreatmentType,
          pi_vTreatmentTitle,
          pi_nTreatmentID,
          pi_vPatientID;  
           
    commit;


exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*get treatment rs by id*/
procedure GetTreatmentRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nTreatmentID           in long,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'SELECT  t.PATIENT_ID,
               t.TREATMENT_ID,
               t.REGION_ID,
               t.SITE_ID,
               t.INITIAL_DATE,
               t.END_DATE,
               t.TREATMENT_TITLE,
               t.TREATMENT_TYPE_ID,
               decode(t.TREATMENT_TYPE_ID, 
                      1, ''Outpatient'', 
                      2, ''Inpatient'', 
                      ''Unknown'') as TREATMENT_TYPE 
         FROM tbicds.PAT_TREATMENT t
        WHERE t.patient_id = :PATIENT_ID 
          AND t.treatment_id = :TREATMENT_ID ';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID,
          pi_nTreatmentID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*get treatment program rs by program id*/
procedure GetTreatmentProgramRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nTreatmentID           in long,
      pi_nProgramID             in long,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'SELECT  t.PATIENT_ID,
               t.TREATMENT_ID,
               t.CPA_ID,
               t.REGION_ID,
               t.SITE_ID,
               t.INITIAL_DATE,
               t.END_DATE,
               t.PROGRAM_ID,
               t2.CPA_TITLE
         FROM tbicds.PAT_TREATMENT_PROGRAM t,
              tbicds.CPA t2
        WHERE t.patient_id = :PATIENT_ID 
          AND t.treatment_id = :TREATMENT_ID 
          AND t.program_id = :PROGRAM_ID 
          AND t2.CPA_ID = t.CPA_ID      
        ORDER BY t.INITIAL_DATE DESC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID,
          pi_nTreatmentID,
          pi_nProgramID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*get treatment program rs by treatment id*/
procedure GetTreatmentProgramRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nTreatmentID           in long,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'SELECT  t.PATIENT_ID,
               t.TREATMENT_ID,
               t.CPA_ID,
               t.REGION_ID,
               t.SITE_ID,
               t.INITIAL_DATE,
               t.END_DATE,
               t.PROGRAM_ID,
               t2.CPA_TITLE
         FROM tbicds.PAT_TREATMENT_PROGRAM t,
              tbicds.CPA t2
        WHERE t.patient_id = :PATIENT_ID 
          AND t.treatment_id = :TREATMENT_ID 
          AND t2.CPA_ID = t.CPA_ID      
        ORDER BY t.INITIAL_DATE DESC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID,
          pi_nTreatmentID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*
gets a recordset of all treatments for this patient
*/
procedure GetTreatmentRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'SELECT  t.PATIENT_ID,
               t.TREATMENT_ID,
               t.TREATMENT_TYPE_ID,
               t.INITIAL_DATE,
               t.END_DATE,
               t.TREATMENT_TITLE,
               t.REGION_ID,
               t.SITE_ID,
               decode(t.TREATMENT_TYPE_ID, 
                      1, ''Outpatient'', 
                      2, ''Inpatient'', 
                      ''Unknown'') as TREATMENT_TYPE 
         FROM tbicds.PAT_TREATMENT t
        WHERE t.patient_id = :PATIENT_ID 
        ORDER BY t.INITIAL_DATE DESC';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*
insert a new patient treatment
*/
procedure InsertTreatment( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                                
                           pi_nRegionID            in number,
                           pi_nSiteID              in number,
                           pi_vPatientID           in varchar2,
                          
                           pi_nTreatmentTypeID     in number,
                           pi_dtInitialDate        in date,
                           pi_dtEndDate            in date,
                           pi_vTreatmentTitle      in varchar2,
                                
                           po_nPatTreatmentID     out number,
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          )
is
    v_nPatTreatmentID number := 0;
    
    v_vSQL long :=

        'insert into tbicds.pat_treatment( PATIENT_ID,
                                           TREATMENT_ID,
                                           TREATMENT_TYPE_ID,
                                           INITIAL_DATE,
                                           END_DATE,
                                           TREATMENT_TITLE,
                                           REGION_ID,
                                           SITE_ID
                                         )
          values(:PATEINT_ID,
                 :TREATMENT_ID,
                 :TREATMENT_TYPE_ID,
                 :INITIAL_DATE,
                 :END_DATE,
                 :TREATMENT_TITLE,   
                 :REGION_ID,
                 :SITE_ID   
                 )';
begin
  
    po_nStatusCode    := 0;
    po_vStatusComment := '';
    po_nPatTreatmentID := 0;
    
    --get a new id
    select SEQ_PATTREATMENTID.nextval into v_nPatTreatmentID from dual;
    
    --execute the SQL
    execute immediate v_vSQL
    using pi_vPatientID,
          v_nPatTreatmentID,
          pi_nTreatmentTypeID,
          pi_dtInitialDate,
          pi_dtEndDate,
          pi_vTreatmentTitle,
          pi_nRegionID,
          pi_nSiteID
          ;  
           
    commit;

    --return the id
    po_nPatTreatmentID := v_nPatTreatmentID;
   

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*
insert a new patient treatment program
*/
procedure InsertTreatmentProgram( pi_vSessionID           in varchar2,
                           pi_vSessionClientIP     in varchar2,
                           pi_nUserID              in number,
                                
                           pi_nRegionID            in number,
                           pi_nSiteID              in number,
                           
                           pi_vPatientID           in varchar2,
                           pi_nPatTreatmentID      in number,
                           pi_nCPAID               in number,
                                                      
                           pi_dtInitialDate        in date,
                           pi_dtEndDate            in date,
                          
                           po_nPatTreatProgID     out number,
                           po_nStatusCode         out number,
                           po_vStatusComment      out varchar2
                          )
is
    v_nPatTreatProgID number := 0;
    
    v_vSQL long :=

        'insert into tbicds.pat_treatment_program( PATIENT_ID,
                                                   TREATMENT_ID,
                                                   PROGRAM_ID,
                                                   CPA_ID,
                                                   INITIAL_DATE,
                                                   END_DATE,
                                                   REGION_ID,
                                                   SITE_ID
                                         )
          values(:PATEINT_ID,
                 :TREATMENT_ID,
                 :PROGRAM_ID,
                 :CPA_ID,
                 :INITIAL_DATE,
                 :END_DATE,
                 :REGION_ID,
                 :SITE_ID   
                 )';
begin
  
    po_nStatusCode    := 0;
    po_vStatusComment := '';
    po_nPatTreatProgID := 0;    
    
    --get a new id
    select SEQ_PATTREATPROGID.nextval into v_nPatTreatProgID from dual;
   
    --execute the SQL
    execute immediate v_vSQL
    using pi_vPatientID,
          pi_nPatTreatmentID,
          v_nPatTreatProgID,
          pi_nCPAID,
          pi_dtInitialDate,
          pi_dtEndDate,
          pi_nRegionID,
          pi_nSiteID
          ;  
           
    commit;

    --return the id
    po_nPatTreatProgID := v_nPatTreatProgID;
   

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

end PCK_PAT_TREATMENT;
/

prompt
prompt Creating package body PCK_PROVIDER
prompt ==================================
prompt
create or replace package body tbicds.PCK_PROVIDER is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*
Get provider recordset
*/
   procedure GetProviderRS(pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        pi_vDIMSID          in varchar2,
                        po_nStatusCode      out number,
                        po_vStatusComment   out varchar2,
                        rs                  out RetRefCursor)
   is
      v_vSQL varchar2(32767) := '';
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSQL := 'select t.provider_id, t.name '
                || 'from tbicds.app_user t, tbicds.fx_user_rights r '
                || 'where t.dims_id = :P0 '
                || 'and r.fx_user_id = t.fx_user_id '
                || 'and r.user_type in (1,2) '
                || 'order by t.name ';
      --open recordset
      open rs for v_vSQL using pi_vDIMSID;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_PROVIDER.GetProviderRS(): ' || sqlErrm;
   end;

end;
/

prompt
prompt Creating package body PCK_PWEVENT
prompt =================================
prompt
create or replace package body tbicds.PCK_PWEVENT is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*gets recent clinics used for events*/
procedure GetRecentClinicRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1500) :=
       
        ' select * 
        from utl_clinic nt
        where nt.clinic_id
        in
        (select distinct(TIU_CLINIC_ID) 
        from pat_pw_event t 
        where t.TIU_CLINIC_ID is not null
        and t.region_id = :REGION_ID
        and t.site_id = :SITE_ID)
        and nt.region_id = :REGION_ID2 and nt.site_id = :SITE_ID2
        order by xfer_date desc';
       
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_nRegionID,
          pi_nSiteID,
          pi_nRegionID,
          pi_nSiteID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;



/*gets recent note titles used for events*/
procedure GetRecentNoteTitleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1500) :=
       
        ' select nt.*,
          decode(nt.is_consult,1,''Y'',''N'') as consult_yn 
          from utl_note_title nt
          where nt.note_title_tag
          in
          (select distinct(TIU_NOTE_TITLE_IEN) 
          from pat_pw_event t 
          where t.tiu_note_id is not null
          and t.region_id = :REGION_ID
          and t.site_id = :SITE_ID)
          and nt.region_id = :REGION_ID2 and nt.site_id = :SITE_ID2
          order by xfer_date desc';
       
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_nRegionID,
          pi_nSiteID,
          pi_nRegionID,
          pi_nSiteID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/***
insert modules into the pat pw event module list
****/
procedure InsertPatPWEventModule (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      pi_nMID                   in number,
      
      po_nEventModuleID         out number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

      v_nIndex number := 0;
      v_vMIDPiece varchar2(4000) := ''; 
      v_vFORPiece varchar2(4000) := '';  
      v_nMID number := 0;   
      v_nModuleFor number := 2;
      
      v_dtOldScheduled date := null;
      v_nPatPWID number := 0;
      v_nDays number := 0;
      v_nEventModuleID number := 0;
   
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    v_nEventModuleID := 0;
    
        
           --get the mid and bump the index
           v_nMID := pi_nMID;
           v_nModuleFor := 3;
           v_nIndex := v_nIndex +1;
           
           select SEQPATPWEVENTMODULEID.Nextval 
           into v_nEventModuleID from dual;
           
           insert into 
           pat_pw_event_module(PATIENT_ID,
                               MID,
                               STATUS,
                               REGION_ID,
                               SITE_ID,
                               DATE_STARTED,
                               DATE_COMPLETED,
                               PAT_PW_ID,
                               INTAKE_ID,
                               MODULE_FOR,
                               SORT_ORDER,
                               PAT_PW_EVENT_ID,
                               DATE_SCHEDULED,
                               PW_EVENT_MODULE_ID)
            values(pi_vPatientID,
                   
                   v_nMID,
                   
                   0,--status
                   
                   (select REGION_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                   
                    (select SITE_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                    
                    null, --date started
                    
                    null, --date completed
                   
                   (select PAT_PW_ID 
                    from pat_pw_event 
                    where pat_pw_event_id = pi_nPatPWEventID),
                   
                    null, --intake_id
                    
                    v_nModuleFor, --module for
                    
                    (select nvl(max(sort_order), 0) + 1 
                       from pat_pw_event_module 
                      where pat_pw_event_id = pi_nPatPWEventID),
                      
                    pi_nPatPWEventID,
                    
                    sysdate,
                    
                    v_nEventModuleID);
                                    
           commit;    
           
           po_nEventModuleID :=  v_nEventModuleID;                          
 
exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*
Insert patient pathway event
*/
procedure InsertPatPWEvent (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
   
      pi_vEventTitle            in varchar2,
      pi_dtEventDate            in date,
      
      po_nPatPWEventID          out number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is
      v_nPatPWEventID number := 0;
   
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    po_nPatPWEventID := 0;
    
    --get a new patient pathway event id
    select SEQPATPWEVENTID.nextval into v_nPatPWEventID from dual;
    
    --insert the event 
    insert into pat_pw_event
                (PATIENT_ID,
                 STATUS,
                 DATE_SCHEDULED,
                 DATE_STARTED,
                 DATE_COMPLETED,
                 REGION_ID,
                 SITE_ID,
                 PAT_PW_ID,
                 EVENT_TITLE,
                 EVENT_DESCR,
                 SORT_ORDER,
                 EVENT_FREQUENCY,
                 PW_EVENT_TYPE_ID,
                 PAT_PW_EVENT_ID,
                 CREATED_BY)
        values(pi_vPatientID,
               0,
               pi_dtEventDate,
               null,
               null,
               pi_nRegionID,
               pi_nSiteID,
               pi_nPatPWID,
               pi_vEventTitle,
               '',
               99,
               null,
               1, --scheduled
               v_nPatPWEventID,
               pi_nUserID);
        
        commit;                  
        
        --return the patpweventid
        po_nPatPWEventID := v_nPatPWEventID;
        
exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Gets todays pathway events associated with a patient
******/
procedure GetTodaysPatPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWID               in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1500) :=
       
        'SELECT t.PATIENT_ID,  
                t.STATUS,
                t.DATE_SCHEDULED,
                t.DATE_STARTED,
                t.DATE_COMPLETED,
                t.REGION_ID,
                t.SITE_ID,
                t.PAT_PW_ID,
                t.event_title,
                t.EVENT_DESCR,
                t.SORT_ORDER,
                t.EVENT_FREQUENCY,
                t.PW_EVENT_TYPE_ID,
                t.PAT_PW_EVENT_ID,
                t.PLAN_PAT_PW_EVENT_ID,
                t.PLAN_TEXT,
                t.NOTE_TEXT,
                t.TIU_DFN,
                t.TIU_DUZ,
                t.TIU_ENCOUNTER_ID,
                t.TIU_CONSULT_IEN,
                t.TIU_COSIGNER_DUZ,
                t.TIU_NOTE_TITLE_IEN,
                t.TIU_NOTE,
                t.TIU_CLINIC_ID,
                t.TIU_DATE_SUBMITTED,
                t.TIU_ENCOUNTER_TYPE,
                t.TIU_NOTE_TITLE,
                t.TIU_LOCATION,
                t.TIU_COSIGNER,
                t.TIU_NOTE_ID,
                t.TIU_CONSULT
                
       FROM tbicds.PAT_PW_EVENT t
       WHERE t.patient_id = :PATIENT_ID 
         and t.pat_pw_id = :PAT_PWID 
         and trunc(t.date_scheduled) = trunc(sysdate) 
         ORDER BY t.DATE_SCHEDULED DESC';
       
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID,
          pi_nPatPWID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*gets the no pathway for a patient*/
procedure GetNoPathwayRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1024) :=
      'select t.* 
         from PAT_PW t 
        where t.patient_id = :PATIENT_ID 
              and t.PW_TYPE_ID = 3';

begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL 
      using pi_vPatientID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*gets all open encounters for a patient*/
procedure GetOpenEncountersRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(2048) :=
      'select to_char(t.date_scheduled,''mm/dd/yyyy HH:MI:SS'') as event_date,
              t.date_completed, t.patient_id, t.tiu_note_title,
              t.pat_pw_event_id,
              t.status,
              t.date_scheduled,
              t.pat_pw_id,
              (select name 
                 from app_user u
              where u.fx_user_id = t.created_by)  as PROVIDER_NAME
              
         from PAT_PW_EVENT t, PAT_PW p
        where t.pat_pw_id = p.pat_pw_id 
              and t.date_completed is null 
              and t.patient_id = :PATIENT_ID 
              and trunc(t.date_scheduled) <= trunc(sysdate) 
              and (( (t.tiu_note_title is not null)
                 or (t.pat_pw_event_id in (select pat_pw_event_id 
                                          from pat_pw_event_module t2 
                                          where t2.date_completed is not null))
                 or (t.note_text is not null))
                 
                 or (t.status = 0 and p.pw_type_id = 3)
                 )
                 
              order by t.date_scheduled desc';

begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL 
      using pi_vPatientID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*updates the intrument date*/
procedure UpdateInstrumentDate (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nIntakeID              in number,
      pi_dtDate                 in date,
                      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

     v_vSQL long :=
      'UPDATE tbicds.PAT_PW_EVENT_MODULE  
       set DATE_STARTED = :DATE_STARTED,
           DATE_COMPLETED = :DATE_COMPLETED 
       where PATIENT_ID = :PATIENT_ID
       and INTAKE_ID = :INTAKE_ID';
       
     v_vSQL2 long :=
      'UPDATE tbicds.DATA_INTAKE  
       set START_DATE = :DATE_STARTED,
           COMPLETE_DATE = :DATE_COMPLETED 
       where PATIENT_ID = :PATIENT_ID
       and INTAKE_ID = :INTAKE_ID';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --execute the sql
    execute immediate v_vSQL 
                using pi_dtDate,
                      pi_dtDate,
                      pi_vPatientID,
                      pi_nIntakeID
                      ;
    
    commit;
    
    --execute the sql setting the modules to completed
    execute immediate v_vSQL2 
                using pi_dtDate,
                      pi_dtDate,
                      pi_vPatientID,
                      pi_nIntakeID
                      ;
    
    commit;
    
exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*get the most recent medical history record*/
procedure GetMedicalHxRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'select t.patient_id,
              t.region_id,
              t.site_id,
              t.pat_pw_id,
              t.pat_pw_event_id,
              t.med_hx_date,
              t.fx_user_id
         from patient_medical_hx t
        where t.patient_id = :PATIENT_ID
          and t.med_hx_date = (select max(med_hx_date) 
                                 from patient_medical_hx 
                                where patient_id = :PATIENT_ID)';

begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID,
          pi_vPatientID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*insert a new medical history record*/
procedure InsertMedicalHx ( pi_vSessionID           in varchar2,
                            pi_vSessionClientIP     in varchar2,
                            pi_nUserID              in number,
                                
                            pi_nRegionID            in number,
                            pi_nSiteID              in number,
                            pi_vPatientID           in varchar2,
                            pi_nPatPWID             in number,
                            pi_nPatPWEventID        in number,
                            
                            po_nStatusCode           out number,
                            po_vStatusComment        out varchar2
                          )
is
    v_nPWEventTypeID number := 0;
    v_nPatPWEventID number := 0;
    v_nSortOrder number := 0;
    
    v_vSQL long :=

        'insert into tbicds.patient_medical_hx( PATIENT_ID,
                                                REGION_ID,
                                                SITE_ID,
                                                PAT_PW_ID,
                                                PAT_PW_EVENT_ID,
                                                MED_HX_DATE,
                                                FX_USER_ID
                                               )
          values(:PATEINT_ID,
                 :REGION_ID,
                 :SITE_ID,
                 :PAT_PW_ID,
                 :PAT_PW_EVENT_ID,
                 :MED_HX_DATE,
                 :FX_USER_ID             
                 )';
begin
  
    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --get a new id
    --select SEQPATPWEVENTID.nextval into v_nPatPWEventID from dual;
    
    --execute the SQL
    execute immediate v_vSQL
    using pi_vPatientID,
          pi_nRegionID,
          pi_nSiteID,
          pi_nPatPWID,
          pi_nPatPWEventID,
          sysdate,
          pi_nUserID;  
           
    commit;

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*get the most recent medical history intake_id*/ 
procedure GetMedicalHxIntakeID( pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,   
                                pi_vPatientID       in varchar2,
                                po_nIntakeID        out number,   
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2
                              )
is

  v_nIntakeID number := 0;

begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    -- get the latest intake_id for the Past Medical History module instrument
    begin
      select max(intake_id)
        into v_nIntakeID
        from data_intake_responses
       where patient_id = pi_vPatientID
         and mid = 3000; -- Past Medical History module instrument
    exception
      when others then
        v_nIntakeID := 0;
    end;
    
    --Return the Intake ID
    po_nIntakeID := v_nIntakeID;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;
                               
/*write note details to tbi cds after commited to MDWS*/
procedure WriteNote (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      
      pi_vDFN                   in varchar2,
      pi_vDUZ                   in varchar2,
      pi_vEncounterID           in varchar2,
      pi_vConsultIEN            in varchar2,
      pi_vCosignerDUZ           in varchar2,
      pi_vNoteTitleIEN          in varchar2,
      pi_vTIUNoteID             in varchar2,
      pi_vTIUNote               in clob,
      pi_nClinicID              in number,
      pi_nEncounterType         in number,
      pi_vNoteTitle             in varchar2,
      pi_vLocation              in varchar2,
      pi_vCosigner              in varchar2,
      pi_vConsult               in varchar2,
      pi_vTBINote               in clob,
                      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

     v_vSQL long :=
      'UPDATE tbicds.pat_pw_event  
       set TIU_DFN = :TIU_DFN,
           TIU_DUZ = :TIU_DUZ,
           TIU_ENCOUNTER_ID = :TIU_ENCOUNTER_ID,
           TIU_CONSULT_IEN = :TIU_CONSULT_IEN,
           TIU_COSIGNER_DUZ = :TIU_COSIGNER_DUZ,
           TIU_NOTE_TITLE_IEN = :TIU_NOTE_TITLE_IEN,
           TIU_NOTE_ID = :TIU_NOTE_ID, 
           TIU_NOTE = :TIU_NOTE,
           TIU_CLINIC_ID = :TIU_CLINIC_ID,
           TIU_DATE_SUBMITTED = :TIU_DATE_SUBMITTED,
           TIU_ENCOUNTER_TYPE = :TIU_ENCOUNTER_TYPE,
           TIU_NOTE_TITLE = :TIU_NOTE_TITLE,
           TIU_LOCATION = :TIU_LOCATION,
           TIU_COSIGNER = :TIU_COSIGNER,
           TIU_CONSULT = :TIU_CONSULT,
           NOTE_TEXT = :NOTE_TEXT,
           STATUS = 2,
           DATE_COMPLETED = :DATE_COMPLETED 
       where PATIENT_ID = :PATIENT_ID
       and PAT_PW_EVENT_ID = :PAT_PW_EVENT_ID';
       
     v_vSQL2 long :=
      'UPDATE tbicds.PAT_PW_EVENT_MODULE  
       set STATUS = 2
       where STATUS = 1  
       AND PATIENT_ID = :PATIENT_ID
       AND PAT_PW_EVENT_ID = :PAT_PW_EVENT_ID';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --execute the sql
    execute immediate v_vSQL 
                using pi_vDFN,
                      pi_vDUZ,
                      pi_vEncounterID,
                      pi_vConsultIEN,
                      pi_vCosignerDUZ,
                      pi_vNoteTitleIEN,
                      pi_vTIUNoteID,
                      pi_vTIUNote,
                      pi_nClinicID,
                      sysdate,
                      pi_nEncounterType,
                      pi_vNoteTitle,
                      pi_vLocation,
                      pi_vCosigner,
                      pi_vConsult,
                      pi_vTBINote,
                      sysdate,
                      pi_vPatientID,
                      pi_nPatPWEventID
                      ;
    
    commit;
    
    --execute the sql setting the modules to completed
    execute immediate v_vSQL2 
                using pi_vPatientID,
                      pi_nPatPWEventID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*save note progress, used while the note is being written but before 
it is commited*/
procedure SaveNoteProgress (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      
      pi_nEncounterType         in number,
      pi_vNoteTitle             in varchar2,
      pi_vLocation              in varchar2,
      pi_vCosigner              in varchar2,
      pi_vConsult               in varchar2,
      pi_vNote                  in clob,
                      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

     v_vSQL long :=
      'UPDATE tbicds.pat_pw_event  
       set TIU_ENCOUNTER_TYPE = :TIU_ENCOUNTER_TYPE,
           TIU_NOTE_TITLE = :TIU_NOTE_TITLE,
           TIU_LOCATION = :TIU_LOCATION,
           TIU_COSIGNER = :TIU_COSIGNER,
           TIU_CONSULT = :TIU_CONSULT,
           NOTE_TEXT = :NOTE_TEXT
       where PATIENT_ID = :PATIENT_ID
       and PAT_PW_EVENT_ID = :PAT_PW_EVENT_ID';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --execute the sql
    execute immediate v_vSQL 
                using pi_nEncounterType,
                      pi_vNoteTitle,
                      pi_vLocation,
                      pi_vCosigner,
                      pi_vConsult,
                      pi_vNote,
                      pi_vPatientID,
                      pi_nPatPWEventID
                      ;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/***
Get all outcome measures associated with an event
***/
procedure GetOutcomeMeasuresRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL long :=
      'select t.patient_id, 
       t.pat_pw_id, 
       t.pat_pw_event_id, 
       t.pw_event_module_id, 
       t.mid,
       t.intake_id,
       t2.module,
              
       (select count(*)  
          from data_intake_responses
         where intake_id = t.intake_id
           and mid = 4042 
           and tid=1
           and qid=1
           and rid=21) as is_goal,
                                       
       (select tdi.complete_date  
          from data_intake tdi
          where tdi.patient_id = t.patient_id
          and tdi.intake_id = t.intake_id
          and tdi.patient_id = t.patient_id 
          and tdi.mid = t.mid 
          and rownum=1) as current_score_date,
          
       (select tds.score   
          from data_intake_score tds
          where tds.patient_id = t.patient_id
          and tds.intake_id = t.intake_id
          and tds.patient_id = t.patient_id
          and tds.mid = t.mid 
          and tds.series = 0
          and rownum=1) as current_score,
          
         (select tds.interpretation   
          from data_intake_score tds
          where tds.patient_id = t.patient_id
          and tds.intake_id = t.intake_id
          and tds.patient_id = t.patient_id 
          and tds.mid = t.mid 
          and tds.series = 0
          and rownum=1) as current_interpretation,
          
         (select pe.event_entry_type_id 
          from pat_pw_event_entry pe,
               stat_event_status es
          where pe.event_status_id = es.event_status_id
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date = 
             (select max(event_date) 
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as event_entry_type_id,
            
         (select es.event_status 
          from pat_pw_event_entry pe,
               stat_event_status es
          where pe.event_status_id = es.event_status_id
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date = 
             (select max(event_date) 
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_status,
            
          (select pe.event_status_id  
          from pat_pw_event_entry pe,
               stat_event_status es
          where pe.event_status_id = es.event_status_id
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date = 
             (select max(event_date) 
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_status_id,
            
          (select es.event_severity  
          from pat_pw_event_entry pe,
               stat_event_severity es
          where pe.event_severity_id = es.event_severity_id 
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date = 
             (select max(event_date) 
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_severity,
            
          (select es.event_severity_id  
          from pat_pw_event_entry pe,
               stat_event_severity es
          where pe.event_severity_id = es.event_severity_id 
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date = 
             (select max(event_date) 
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_severity_id,
                             
         (select count(*) 
          from pat_pw_event_entry pe,
                stat_event_status es
          where pe.event_status_id = es.event_status_id
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and rownum = 1) as current_reviewed,
            
       (select tdi.complete_date - 10  
          from data_intake tdi
          where tdi.patient_id = t.patient_id
          and tdi.intake_id = t.intake_id
          and tdi.patient_id = t.patient_id 
          and tdi.mid = t.mid 
          and rownum=1) as prev_score_date,
          
          PCK_PWEVENT.GetPrevIntakeScore(t.mid, t.patient_id, t.intake_id) as prev_score,
          
         (select tds.interpretation || ''PREV''   
          from data_intake_score tds
          where tds.patient_id = t.patient_id
          and tds.intake_id = t.intake_id 
          and tds.patient_id = t.patient_id 
          and tds.mid = t.mid 
          and tds.series = 0
          and rownum=1) as prev_interpretation,
          
          (select nvl(tt.status, 0) 
             from pat_pw_event tt 
           where tt.pat_pw_event_id = :PAT_PW_EVENT_ID) 
           as event_status
          
          from PAT_PW_EVENT_MODULE t,
               intake_module t2
          where t.patient_id = :PATIENT_ID
            and t.pat_pw_event_id = :PAT_PW_EVENT_ID
            and t2.mid = t.mid 
            and nvl(t.intake_id,-1) > 0 
       order by t2.module, t.date_scheduled';

begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_nPatPWEventID,
          pi_vPatientID,
          pi_nPatPWEventID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/***
Get all scores for an intake
***/
procedure GetIntakeScoreRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nIntakeID              in number,
      pi_nMID                   in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'select t.patient_id,
              t.mid,
              t.intake_id,
              t.series,
              t.score,
              PCK_PWEVENT.GetPrevIntakeSubscaleScore(t.mid, t.patient_id, t.intake_id, t.series) as PREV_SCORE,
              t.interpretation,
              t.description
         from data_intake_score t
        where t.patient_id = :PATIENT_ID
          and t.intake_id = :INTAKE_ID
          and t.MID = :MID 
     order by t.series asc';

begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID,
          pi_nIntakeID,
          pi_nMID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/******
get all event entries for an event
******/  
procedure GetEventEntryRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'SELECT t.PAT_PW_EVENT_ENTRY_ID,
              t.PATIENT_ID,
              t.PAT_PW_ID,
              t.PAT_PW_EVENT_ID,
              t.EVENT_ENTRY_TYPE_ID,
              t.EVENT_COMMENT,
              t.FX_USER_ID,
              t.EVENT_DATE,
              t.EVENT_STATUS_ID,
              t.EVENT_SEVERITY_ID,
              t.PW_EVENT_MODULE_ID,
              t2.NAME as USER_NAME,
              t2.TITLE as USER_TITLE,
              t3.EVENT_ENTRY_TYPE,
              
              (select tim.module from 
               intake_module tim,
               pat_pw_event_module tpe 
               where tpe.PW_EVENT_MODULE_ID = t.PW_EVENT_MODULE_ID 
               and tim.mid = tpe.mid) as module, 
              
              (select count(*) from
                tbicds.pat_pw_event_entry
                where PAT_PW_EVENT_ENTRY_ID = t.PAT_PW_EVENT_ENTRY_ID
                and fx_user_id = :FX_USER_ID) as allow_edit,
              (select nvl(tt.status,0) from
                pat_pw_event tt
                where tt.pat_pw_event_id = :PAT_PW_EVENT_ID) as event_status
                
       FROM tbicds.pat_pw_event_entry t,
            tbicds.app_user t2,
            tbicds.stat_event_entry_type t3
       where t.pat_pw_event_id = :PAT_PW_EVENT_ID 
       and t.patient_id = :PATIENT_ID
       and t2.fx_user_id = t.fx_user_id 
       and t3.event_entry_type_id = t.event_entry_type_id 
       order by event_date desc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_nUserID,
          pi_nPatPWEventID, 
          pi_nPatPWEventID,
          pi_vPatientID;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/******
get event entry types Subjective, Objective, Assessment, Plan etc...
******/  
procedure GetEventEntryTypeRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*
       FROM tbicds.STAT_EVENT_ENTRY_TYPE t 
       order by sort_order asc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/******
get event statuses Better, Same, Worse etc...
******/  
procedure GetEventStatusRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*
       FROM tbicds.stat_event_status t 
       order by sort_order asc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/******
get event severities: mild, moderate, severe etc...
******/  
procedure GetEventSeverityRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*
       FROM tbicds.stat_event_severity t 
       order by sort_order asc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
    for v_vSQL;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*
insert a new pathway event
*/
procedure InsertPWEvent ( pi_vSessionID           in varchar2,
                          pi_vSessionClientIP     in varchar2,
                          pi_nUserID              in number,
                                
                          pi_nRegionID            in number,
                          pi_nSiteID              in number,
                          pi_vPatientID           in varchar2,
                          pi_nPatPWID             in number,
                          pi_vEventTitle          in varchar2,
                          pi_dtEventDate          in varchar2,
                          pi_nRelatedEventID      in number,
                                
                          po_nPatPWEventID           out number,
                          po_nStatusCode           out number,
                          po_vStatusComment        out varchar2
                          )
is
    v_nPWEventTypeID number := 0;
    v_nPatPWEventID number := 0;
    v_nSortOrder number := 0;
    
    v_vSQL long :=

        'insert into tbicds.pat_pw_event( PATIENT_ID,
                                          STATUS,
                                          DATE_SCHEDULED,
                                          REGION_ID,
                                          SITE_ID,
                                          PAT_PW_ID,
                                          EVENT_TITLE,
                                          SORT_ORDER,
                                          EVENT_FREQUENCY,
                                          PW_EVENT_TYPE_ID,
                                          PAT_PW_EVENT_ID,
                                          MERGED
                                         )
          values(:PATEINT_ID,
                 :STATUS,
                 :DATE_SCHEDULED,
                 :REGION_ID,
                 :SITE_ID,
                 :PAT_PW_ID,
                 :EVENT_TITLE,
                 :SORT_ORDER,
                 :EVENT_FREQUENCY,
                 :PW_EVENT_TYPE_ID,
                 :PAT_PW_EVENT_ID,
                 :MERGED                 
                 )';
begin
  
    po_nStatusCode    := 0;
    po_vStatusComment := '';
    po_nPatPWEventID := 0;
    
    --get a new id
    select SEQPATPWEVENTID.nextval into v_nPatPWEventID from dual;
    
    --get event type
    select t.pw_event_type_id, 
           t.sort_order into 
           v_nPWEventTypeID, v_nSortOrder 
    from pat_pw_event t
    where t.pat_pw_event_id = pi_nRelatedEventID
    and t.patient_id = pi_vPatientID;
  
    --bump sort order for all records after related record
    update pat_pw_event tt
    set tt.sort_order = sort_order + 1
    where tt.patient_id = pi_vPatientID 
    and tt.pat_pw_event_id = pi_nRelatedEventID
    and tt.sort_order > v_nSortOrder;
    
    --execute the SQL
    execute immediate v_vSQL
    using pi_vPatientID,
          0,
          pi_dtEventDate,
          pi_nRegionID,
          pi_nSiteID,
          pi_nPatPWID,
          pi_vEventTitle,
          v_nSortOrder + 1,
          0,
          v_nPWEventTypeID,
          v_nPatPWEventID,
          0;  
           
    commit;

    --return the id
    po_nPatPWEventID := v_nPatPWEventID;
   

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/******
insert an event entry 
******/  
procedure InsertPWEventEntry (  pi_vSessionID             in varchar2,
                                pi_vSessionClientIP       in varchar2,
                                pi_nUserID                in number,
                                
                                pi_vPatientID             in varchar2,
                                pi_nPatPWEventID          in number,
                                pi_nPWEventModuleID       in number,
                                pi_nEventEntryTypeID      in number,
                                pi_dtEventDate            in date,
                                pi_vEventEntryComment     in varchar2,
                                pi_nEventStatusID         in number,
                                pi_nEventSeverityID       in number,
                                
                                po_nEventEntryID          out number,
                                
                                po_nStatusCode           out number,
                                po_vStatusComment        out varchar2
                             )
is

     v_vSQL long :=

        'insert into tbicds.pat_pw_event_entry(PAT_PW_EVENT_ENTRY_ID,
                                              PATIENT_ID,
                                              PAT_PW_ID,
                                              PAT_PW_EVENT_ID,
                                              EVENT_ENTRY_TYPE_ID,
                                              EVENT_COMMENT,
                                              FX_USER_ID,
                                              EVENT_DATE,
                                              EVENT_STATUS_ID,
                                              EVENT_SEVERITY_ID,
                                              PW_EVENT_MODULE_ID)
          values(:PAT_PW_EVENT_ENTRY_ID,
                 :PATIENT_ID,
                 :PAT_PW_ID,
                 :PAT_PW_EVENT_ID,
                 :EVENT_ENTRY_TYPE_ID,
                 :EVENT_COMMENT,
                 :FX_USER_ID,
                 :EVENT_DATE,
                 :EVENT_STATUS_ID,
                 :EVENT_SEVERITY_ID,
                 :PW_EVENT_MODULE_ID
                 )';
                 
     
      v_nEntryID number := 0;
      v_nPatPWID number := 0;
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
  
    po_nEventEntryID := 0;
    v_nEntryID := 0;
    
    --get a new id
    select seqpatpwentryid.nextval into v_nEntryID from dual;
    
    --get pat pw id
    select t.pat_pw_id into v_nPatPWID 
    from pat_pw_event t
    where t.pat_pw_event_id = pi_nPatPWEventID;
  
    --execute the SQL
    execute immediate v_vSQL 
    using v_nEntryID,
          pi_vPatientID,
          v_nPatPWID,
          pi_nPatPWEventID,
          pi_nEventEntryTypeID,
          pi_vEventEntryComment,
          pi_nUserID,
          pi_dtEventDate,
          pi_nEventStatusID,
          pi_nEventSeverityID,
          pi_nPWEventModuleID;
           
    commit;

    --return the id
    po_nEventEntryID := v_nEntryID;
   

exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/******
update an event entry 
******/  
procedure UpdatePWEventEntry (  pi_vSessionID             in varchar2,
                                pi_vSessionClientIP       in varchar2,
                                pi_nUserID                in number,
                                
                                pi_nEventEntryID          in number,
                                pi_nPWEventModuleID       in number,
                                pi_dtEventDate            in date,
                                pi_vEventEntryComment     in varchar2,
                                pi_nEventStatusID         in number,
                                pi_nEventSeverityID       in number,
                             
                                po_nStatusCode           out number,
                                po_vStatusComment        out varchar2
                             )
is

     v_vSQL long :=

        'update tbicds.pat_pw_event_entry
         set event_comment = :EVENT_COMMENT,
         event_date = :EVENT_DATE,
         event_status_id = :EVENT_STATUS_ID,
         event_severity_ID = :EVENT_SEVERITY_ID
         where PAT_PW_EVENT_ENTRY_ID = :PAT_PW_EVENT_ENTRY_ID
         ';
     
      v_nEventEntryTypeID number := 0;
      v_nEventID number :=0;
     
 begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';  
  
    --get the type of entry
    select t.event_entry_type_id into v_nEventEntryTypeID
    from tbicds.pat_pw_event_entry t
    where t.pat_pw_event_entry_id = pi_nEventEntryID;
    
    --get the event id
    select t.pat_pw_event_id into v_nEventID
    from tbicds.pat_pw_event_entry t
    where t.pat_pw_event_entry_id = pi_nEventEntryID;    
 
    --execute the SQL
    execute immediate v_vSQL 
    using pi_vEventEntryComment,
          pi_dtEventDate,
          pi_nEventStatusID,
          pi_nEventSeverityID,
          pi_nEventEntryID;
           
    commit;
    
exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*
update the plan portion of the event
*/
procedure UpdatePWEventPlan (  pi_vSessionID             in varchar2,
                               pi_vSessionClientIP       in varchar2,
                               pi_nUserID                in number,
                               
                               pi_nPatPWEventID          in number,
                               pi_nPatPWPlanEventID      in number,
                               pi_vPlanText              in clob,
                               
                               po_nStatusCode           out number,
                               po_vStatusComment        out varchar2
                             )
is

     v_vSQL long :=

        'update tbicds.pat_pw_event
         set plan_text = :PLAN_TEXT,
         PLAN_PAT_PW_EVENT_ID = :PLAN_PAT_PW_EVENT_ID
         where PAT_PW_EVENT_ID = :PAT_PW_EVENT_ID
         ';
     
 begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';  
  
    --execute the SQL
    execute immediate v_vSQL 
    using pi_vPlanText,
          pi_nPatPWPlanEventID,
          pi_nPatPWEventID;
           
    commit;
    
exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/***
delete an event entry
***/
procedure DeletePWEventEntry (  pi_vSessionID             in varchar2,
                                pi_vSessionClientIP       in varchar2,
                                pi_nUserID                in number,
                                
                                pi_nEventEntryID          in number,
                                po_nStatusCode           out number,
                                po_vStatusComment        out varchar2
                             )
is

     v_vSQL long :=

        'delete from tbicds.pat_pw_event_entry
         where PAT_PW_EVENT_ENTRY_ID = :PAT_PW_EVENT_ENTRY_ID
         ';
     
 begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';  
  
    --execute the SQL
    execute immediate v_vSQL 
    using pi_nEventEntryID;
           
    commit;
    
exception
    when others then
      rollback;
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/***
Gets the previous score value for a mid
***/
function GetPrevIntakeScore(pi_nMID in number,
                            pi_vPatientID in varchar2,
                            pi_nIntakeID in number)
  
 return number
 
 is
 
   v_nScore number := 0;
   
 begin
   
 if pi_nMID != 4042 then
   
   select score into v_nScore 
   from 
      (select s1.score   
         from data_intake_score s1,
              data_intake s2
        where s2.patient_id = s1.patient_id
          and s2.intake_id = s1.intake_id
          and s2.mid = s2.mid
            
          and s1.mid = pi_nMID
          and s1.patient_id = pi_vPatientID 
          and s1.series = 0 
            
          and s2.complete_date < 
                     
          (select complete_date   
            from data_intake
           where patient_id = pi_vPatientID
             and intake_id = pi_nIntakeID
             and mid = pi_nMID 
             and rownum = 1 ) 
      order by s2.complete_date desc
      )where rownum = 1; 

else
  
 select score into v_nScore 
   from 
      (select s1.score   
         from data_intake_score s1,
              data_intake s2
        where s2.patient_id = s1.patient_id
          and s2.intake_id = s1.intake_id
          and s2.mid = s2.mid
            
          and s1.mid = pi_nMID
          and s1.patient_id = pi_vPatientID 
          and s1.series = 0 
          
            and ((select rid 
              from data_intake_responses 
             where intake_id = s1.intake_id 
               and tid=1 
               and qid=1 ) != 21)
            
          and s2.complete_date < 
                     
          (select complete_date   
            from data_intake
           where patient_id = pi_vPatientID
             and intake_id = pi_nIntakeID
             and mid = pi_nMID 
             and rownum = 1 ) 
      order by s2.complete_date desc
      )where rownum = 1; 

  end if;

    
    return v_nScore;

exception
    when others then
    return null;  
end;

 /***
 Gets the previous score value for the subscale of a mid
 ***/
 function GetPrevIntakeSubscaleScore(pi_nMID in number,
                                     pi_vPatientID in varchar2,
                                     pi_nIntakeID in number,
                                     pi_nSeries in number)
  
 return number
 
 is
 
   v_nScore number := 0;
   
 begin
   
 if pi_nMID != 4042 then
   
   select s.score into v_nScore
    from data_intake_score s
   where s.patient_id = pi_vPatientID
     and s.mid = pi_nMID
     and s.series = pi_nSeries
     and s.intake_id =
          (select t.intake_id
             from
               (select l.intake_id
                  from data_intake l
                 where l.mid = pi_nMID
                   and l.patient_id = pi_vPatientID 
                   and l.complete_date <              
                         (select complete_date   
                           from data_intake
                          where patient_id = pi_vPatientID
                            and intake_id = pi_nIntakeID
                            and mid = pi_nMID 
                            and rownum = 1) 
                 order by l.complete_date desc) t
           where rownum = 1);
 else
   
 select s.score into v_nScore
    from data_intake_score s
   where s.patient_id = pi_vPatientID
     and s.mid = pi_nMID
     and s.series = pi_nSeries
     and s.intake_id =
          (select t.intake_id
             from
               (select l.intake_id
                  from data_intake l
                 where l.mid = pi_nMID
                   and l.patient_id = pi_vPatientID 
                   
                   and ((select rid 
                  from data_intake_responses 
                 where intake_id = l.intake_id 
                   and tid=1 
                   and qid=1 ) != 21)
               
                   and l.complete_date <              
                         (select complete_date   
                           from data_intake
                          where patient_id = pi_vPatientID
                            and intake_id = pi_nIntakeID
                            and mid = pi_nMID 
                            and rownum = 1) 
                 order by l.complete_date desc) t
           where rownum = 1);
 
 end if;
    
    return v_nScore;

exception
    when others then
    return null;  
end;

/***
 Gets the next event id after an event
***/
function GetNextPatPWEventID(pi_nPatPWEventID in number,
                             pi_vPatientID in varchar2)
  
 return number
 
 is
 
   v_nPatPWID number := 0;
   v_nPatPWEventID number := 0;
   
 begin
   
   --get the patient pathway id
   select pat_pw_id into v_nPatPWID
     from pat_pw_event
    where pat_pw_event_id = pi_nPatPWEventID 
      and patient_id = pi_vPatientID;
   
   --get the next event id after this event id
   --exclude closed events
   select pat_pw_event_id into v_nPatPWEventID 
   from 
      (select t.pat_pw_event_id   
         from pat_pw_event t
        where t.patient_id = pi_vPatientID
          and t.pat_pw_id = v_nPatPWID
          and nvl(t.status,0) != 2  
          and t.date_scheduled > (select date_scheduled 
                                     from pat_pw_event 
                                    where pat_pw_id = v_nPatPWID
                                      and patient_id = pi_vPatientID 
                                      and pat_pw_event_id = pi_nPatPWEventID )
      order by t.date_scheduled asc
      )where rownum = 1; 

    
    return v_nPatPWEventID;

exception
    when others then
    return null;  
end;

/*****
Gets next pathway event associated with a patient
******/
procedure GetNextPatPWEventRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vPatientID             in varchar2,
      pi_nPatPWEventID          in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(1500) :=
       
        'SELECT t.PATIENT_ID,	
                t.STATUS,
                t.DATE_SCHEDULED,
                t.DATE_STARTED,
                t.DATE_COMPLETED,
                t.REGION_ID,
                t.SITE_ID,
                t.PAT_PW_ID,
                t.event_title,
                t.EVENT_DESCR,
                t.SORT_ORDER,
                t.EVENT_FREQUENCY,
                t.PW_EVENT_TYPE_ID,
                t.PAT_PW_EVENT_ID

       FROM tbicds.PAT_PW_EVENT t
       WHERE t.patient_id = :PATIENT_ID 
         and t.pat_pw_event_id = :PAT_PW_EVENT_ID 
         ORDER BY t.DATE_SCHEDULED ASC';
         
    v_nNextEventID number := 0;
       
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    v_nNextEventID := PCK_PWEVENT.GetNextPatPWEventID(pi_nPatPWEventID,
                                                      pi_vPatientID);
    
    --open the result set
     open rs 
      for v_vSQL
    using pi_vPatientID,
          v_nNextEventID;
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


end PCK_PWEVENT;
/

prompt
prompt Creating package body PCK_QUESTIONNAIRES
prompt ========================================
prompt
create or replace package body tbicds.PCK_QUESTIONNAIRES is
/* Copyright 2015 Intellica Corporation.  

This software is protected by FAR Subpart 27.4 - Rights in Data and Copyrights and 
international treaties.  The software was produced by Intellica Corporation of 
San Antonio, Texas for the Veterans Administration (VA) under Contract Number 
VA118-14-C-0015, Project Number TAC-16-28335 and Project Title, 
'Traumatic Brain Injury Clinical Decision Support (TBI CDS) Implementation'.  
Contract dates: 8 May 2014 - 4 January 2016.  This software was finalized 
and uploaded to the VA's Open Source Electronic Health Record Alliance (OSEHRA) 
on 31 December 2015.  Unauthorized reproduction or distribution of this software 
or any portion of it may result in severe civil and criminal penalties and will 
be prosecuted to the maximum possible extent of the law.

For licensing information contact:  info@intellicacorp.com 
*/
  /*Gets and returns a recordset from INTAKE_MODULE for the passed in module id.*/
  procedure GetModuleRS(pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        pi_nMID             in number,
                        po_nStatusCode      out number,
                        po_vStatusComment   out varchar2,
                        rs                  out RetRefCursor) 
 is
  
    v_vSQL varchar2(32767) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || ' select * ';
    v_vSQL := v_vSQL || '   from intake_module t ';
    v_vSQL := v_vSQL || '  where t.active = 1 ';
    v_vSQL := v_vSQL || '    and t.mid = :MID ';
  
    open rs for v_vSQL
      using pi_nMID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

  /*Gets and returns a recordset from INTAKE_TOPIC for the passed in module id.*/
  procedure GetModuleTopicRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_nMID             in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor) 
 is
  
    v_vSQL varchar2(32767) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || ' select * ';
    v_vSQL := v_vSQL || '   from intake_topic t ';
    v_vSQL := v_vSQL || '  where t.active = 1 ';
    v_vSQL := v_vSQL || '    and t.mid = :MID ';
    v_vSQL := v_vSQL || '  order by t.tid';
  
    open rs for v_vSQL
      using pi_nMID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

  /*Gets and returns a recordset of questions from INTAKE_QUESTION
  for the passed in module id, topic id.*/
  procedure GetQuestionRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_nMID             in number,
                          pi_nTID             in number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor) 
 is
  
    v_vSQL varchar2(32767) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || ' select * ';
    v_vSQL := v_vSQL || '   from intake_question t ';
    v_vSQL := v_vSQL || '  where t.active = 1 ';
    v_vSQL := v_vSQL || '    and t.mid = :MID ';
    v_vSQL := v_vSQL || '    and t.tid = :TID ';
    v_vSQL := v_vSQL || '  order by t.mid, t.tid, t.qid ';
  
    open rs for v_vSQL
      using pi_nMID, pi_nTID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

  /*Gets and returns a recordset of responses from INTAKE_RESPONSE
  for the passed in module id, topic id, question id.*/
  procedure GetResponseRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_nMID             in number,
                          pi_nTID             in number,
                          pi_nQID             in number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor) 
 is
  
    v_vSQL varchar2(32767) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || ' select t.*, ';
    v_vSQL := v_vSQL || '        REGEXP_REPLACE(t.response, ''<.*?>'') as response_plain, ';
    v_vSQL := v_vSQL || '        REGEXP_REPLACE(REGEXP_REPLACE(t.response, ''<.*?>''), '','', ''**"**'') as response_checkbox ';
    v_vSQL := v_vSQL || '   from intake_response t ';
    v_vSQL := v_vSQL || '  where t.active = 1 ';
    v_vSQL := v_vSQL || '    and t.mid = :MID ';
    v_vSQL := v_vSQL || '    and t.tid = :TID ';
    v_vSQL := v_vSQL || '    and t.qid = :QID ';
    v_vSQL := v_vSQL || '  order by t.mid, t.tid, t.qid, t.rid ';
  
    open rs for v_vSQL
      using pi_nMID, pi_nTID, pi_nQID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

  /*Gets and returns a recordset of responses that have skip rules
  for the passed in module id.*/
  procedure GetSkipPatternRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_nMID             in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor) 
  is
  
    v_vSQL varchar2(32767) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || ' select t.* ';
    v_vSQL := v_vSQL || '   from INTAKE_RESPONSE t ';
    v_vSQL := v_vSQL || '  where t.mid = :MID ';
    v_vSQL := v_vSQL || '    and t.active = 1 ';
    v_vSQL := v_vSQL ||
              '    and (t.skip_show is not null or t.skip_hide is not null) ';
    v_vSQL := v_vSQL || '  order by t.rid ';
  
    open rs for v_vSQL
      using pi_nMID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

  /*Gets and returns a recordset of responses (textboxes) that have masks
  for the passed in module id.*/
  procedure GetMaskRS(pi_vSessionID       in varchar2,
                      pi_vSessionClientIP in varchar2,
                      pi_nUserID          in number,
                      pi_nMID             in number,
                      po_nStatusCode      out number,
                      po_vStatusComment   out varchar2,
                      rs                  out RetRefCursor) 
 is
  
    v_vSQL varchar2(32767) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || ' select t.* ';
    v_vSQL := v_vSQL || '   from INTAKE_RESPONSE t ';
    v_vSQL := v_vSQL || '  where t.mid = :MID ';
    v_vSQL := v_vSQL || '    and t.active = 1 ';
    v_vSQL := v_vSQL || '    and t.mask is not null ';
    v_vSQL := v_vSQL || '  order by t.rid ';
  
    open rs for v_vSQL
      using pi_nMID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

  /*Gets and returns a recordset from intake_static_data table to populate 
  responses of type combo*/
  procedure GetStatData(pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        pi_nMID             in number,
                        pi_nTID             in number,
                        pi_nQID             in number,
                        pi_nRID             in number,
                        po_nStatusCode      out number,
                        po_vStatusComment   out varchar2,
                        rs                  out RetRefCursor) 
 is
  
    v_vSQL        varchar2(32767) := '';
    v_vSQL_FILTER varchar2(32767) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    begin
      select t.stat_load_filter
        into v_vSQL_FILTER
        from intake_response t
       where t.mid = pi_nMID
         and t.tid = pi_nTID
         and t.qid = pi_nQID
         and t.rid = pi_nRID;
    exception
      when others then
        v_vSQL_FILTER := '';
    end;
  
    v_vSQL := v_vSQL || ' select t.* ';
    v_vSQL := v_vSQL || '   from INTAKE_STATIC_DATA t ';
    v_vSQL := v_vSQL || '  where t.active = 1 ';
    v_vSQL := v_vSQL || '    and ';
    v_vSQL := v_vSQL || v_vSQL_FILTER;
  
    open rs for v_vSQL;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

  /*Get the next undone assigned module for the patient. */
  procedure GetNextModuleRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vPatientID       in varchar2,
                          pi_vSiteID          in varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor) 
  is
  
    v_vSQL varchar2(32767) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    v_vSQL := v_vSQL || ' select * from (';
    v_vSQL := v_vSQL || ' select t.*, m.sort_order ';
    v_vSQL := v_vSQL || '   from patient_module t, intake_module_group_mid m ';
    v_vSQL := v_vSQL || '  where t.patient_id = :PATIENT_ID ';
    v_vSQL := v_vSQL || '    and t.status = 0 ';
    v_vSQL := v_vSQL || '    and t.mid = m.mid ';
    v_vSQL := v_vSQL || '    and t.module_group_id = m.module_group_id ';
    v_vSQL := v_vSQL || '  order by m.sort_order ';
    v_vSQL := v_vSQL || ' ) ';
    v_vSQL := v_vSQL || ' where ROWNUM < 2 ';
  
    open rs for v_vSQL
      using pi_vPatientID;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;
  
  /* gets a new intake_id for the module */
  procedure GetNewIntakeID(pi_vSessionID       in varchar2,
                      pi_vSessionClientIP in varchar2,
                      pi_nUserID          in number,
                      po_nStatusCode      out number,
                      po_vStatusComment   out varchar2,
                      rs                  out RetRefCursor) 
 is
 
   v_seqintakeid number;
 
 begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    select seqintakeid.nextval into v_seqintakeid from dual;
  
    open rs for 
      select v_seqintakeid as intake_id from dual;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

end PCK_QUESTIONNAIRES;
/

prompt
prompt Creating package body PCK_REFERRAL_CLINIC
prompt =========================================
prompt
create or replace package body tbicds.PCK_REFERRAL_CLINIC is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   /*
   get referral clinic recordset
   */
   procedure GetReferralClinicRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nStatReferralID  in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select * from tbicds.stat_referral where stat_referral_id = :P0 ';
      open rs for v_vSql using pi_nStatReferralID;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_REFERRAL_CLINIC.GetReferralClinicRS(): ' || sqlErrm;
   end;

   /*
   Get referral clinic lookup recordset
   */
   procedure GetReferralClinicLookUpRS(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2,
                                      rs                  out RetRefCursor) 
   is
      strSQL varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      strSQL := 'select t.* from tbicds.stat_referral t where t.active = 1';
      open rs for strSQL;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_REFERRAL_CLINIC.GetReferralClinicLookUpRS(): ' || sqlErrm;
   end;

   /*
   Insert a referral clinic
   */
   procedure InsertReferralClinic(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_vReferralDesc    in varchar2,
                                 pi_vReferralText    in varchar2,
                                 pi_vProviderName in varchar2,
                                 pi_vAddress      in varchar2,
                                 pi_vCity         in varchar2,
                                 pi_nStateID      in number,
                                 pi_vPostalCode   in varchar2,
                                 pi_vPhone        in varchar2,
                                 pi_vFax          in varchar2,
                                 po_nReferralID    out number,
                                 po_nStatusCode    out number,
                                 po_vStatusComment out varchar2)
   is
      v_vSql                               varchar2(4000);
      v_nReferralID number;
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      po_nReferralID    := -1;
   
      --get a new encounter_intake_id
      v_vSql := 'select tbicds.SEQREFERRALID.Nextval from dual';
      execute immediate v_vSql into v_nReferralID;
      
      v_vSql := 'insert into tbicds.stat_referral ('
                || 'stat_referral_id, stat_referral_desc, stat_referral_text, provider_name, street_address, '
                || 'city, state, postal_code, phone, fax) '
                || 'values ('
                || ':P0, :P1, :P2, :P3, :P4, :P5, :P6, :P7, :P8, :P9) ';
      execute immediate v_vSql using 
         v_nReferralID, pi_vReferralDesc, pi_vReferralText, pi_vProviderName, pi_vAddress,
         pi_vCity, pi_nStateID, pi_vPostalCode, pi_vPhone, pi_vFax;
      commit;
      
      po_nReferralID := v_nReferralID;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_REFERRAL_CLINIC.InsertReferralClinic(): ' || sqlErrm;
   end;

   /*
   Update a referral clinic
   */
   procedure UpdateReferralClinic(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_nReferralID      in number,
                                 pi_vReferralDesc    in varchar2,
                                 pi_vReferralText    in varchar2,
                                 pi_vProviderName in varchar2,
                                 pi_vAddress      in varchar2,
                                 pi_vCity         in varchar2,
                                 pi_nStateID      in number,
                                 pi_vPostalCode   in varchar2,
                                 pi_vPhone        in varchar2,
                                 pi_vFax          in varchar2,
                                 po_nStatusCode    out number,
                                 po_vStatusComment out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'update tbicds.stat_referral set '
                || 'stat_referral_desc = :P0, '
                || 'stat_referral_text = :P1, '
                || 'provider_name = :P2, '
                || 'street_address = :P3, '
                || 'city = :P4, '
                || 'state = :P5, '
                || 'postal_code = :P6, '
                || 'phone = :P7, '
                || 'fax = :P8 '
                || 'where stat_referral_id = :P9 ';
      execute immediate v_vSql using
         pi_vReferralDesc, pi_vReferralText, pi_vProviderName, pi_vAddress, pi_vCity,
         pi_nStateID, pi_vPostalCode, pi_vPhone, pi_vFax, pi_nReferralID;
      commit;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_REFERRAL_CLINIC.UpdateReferralClinic(): ' || sqlErrm;
   end;

   /*
   Discontinue a referral clinic
   */
   procedure DiscontinueReferralClinic(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      pi_nReferralID      in number,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := PCK_COMMON.c_nResultStatus_Success;
      po_vStatusComment := '';
      
      v_vSql := 'update tbicds.stat_referral set active = 0 where stat_referral_id = :P0 ';
      execute immediate v_vSql using pi_nReferralID;
      commit;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_REFERRAL_CLINIC.DiscontinueReferralClinic(): ' || sqlErrm;
   end;

end;
/

prompt
prompt Creating package body PCK_REGION_SITE
prompt =====================================
prompt
CREATE OR REPLACE PACKAGE BODY TBICDS.PCK_REGION_SITE is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*****
Description: Gets regions
******/
procedure GetRegionRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out refCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*
       FROM utl_region t
       order by upper(t.region_name) asc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs for v_vSQL;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*****
Description: Gets region sites
******/
procedure GetSiteRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nRegionID              in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out refCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*
       FROM utl_site t
       WHERE t.region_id = :region_id
       order by upper(t.site_name) asc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs for v_vSQL using pi_nregionid;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
 
end;

/*****
Description: gets the site and region matching the server 
and port passed in used when accessing the site from the CPRS tools menu
******/
procedure GetSiteRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vSRV                   in varchar2,
      pi_vPORT                  in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out refCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*, t2.region_name 
       FROM utl_site t, utl_region t2 
       WHERE lower(t.srv) = lower(:SRV)
       and lower(t.port) = lower(:PORT)
       and t.region_id = t2.region_id
       order by upper(t.site_name) asc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs for v_vSQL using pi_vSRV, pi_vPORT;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
 
end;

/*gets all sites*/
procedure GetSiteRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out refCursor
      )
is

     v_vSQL varchar2(500) :=
      'SELECT t.*, t2.region_name 
       FROM utl_site t, utl_region t2 
       WHERE t.region_id = t2.region_id
       order by upper(t.site_name) asc';
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs for v_vSQL;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
 
end;

END;
/

prompt
prompt Creating package body PCK_REPORTS
prompt =================================
prompt
create or replace package body tbicds.PCK_REPORTS is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*gets the admission intake id, 
only include intakes that have been reviewed*/
function GetAdmissionIntakeID(pi_nMID in number,
                              pi_vPatientID in varchar2,
                              pi_dtStart in date,
                              pi_dtEnd in date)
  
 return number
 
 is
 
   v_nID number := null;
   
 begin
   
   --mid is not FIM, FIM is handled slightly different
   if pi_nMID != 4042 then 
     
     select intake_id into v_nID 
     from 
          (select di.intake_id 
             from data_intake di
            where di.patient_id = pi_vPatientID 
              and mid = pi_nMID 
              and trunc(di.complete_date) >= pi_dtStart
              and trunc(di.complete_date) <= pi_dtEnd
              
              --intake must be reviewed
              and di.intake_id in (select intake_id 
                                   from pat_pw_event_module em 
                                   where em.patient_id = pi_vPatientID 
                                     and em.pw_event_module_id 
                                     in (select pw_event_module_id 
                                          from pat_pw_event_entry)
                                        )
              
         order by di.complete_date asc
           )
     where rownum = 1; 
   
   else
     
      --FIM MID 4042 intake cannot be FIM goal 
      select intake_id into v_nID 
       from 
            (select di.intake_id 
               from data_intake di
              where di.patient_id = pi_vPatientID 
                and mid = pi_nMID 
                and trunc(di.complete_date) >= pi_dtStart
                and trunc(di.complete_date) <= pi_dtEnd
                
                --intake must be reviewed
                and di.intake_id in (select intake_id 
                                     from pat_pw_event_module em 
                                     where em.patient_id = pi_vPatientID 
                                       and em.pw_event_module_id 
                                       in (select pw_event_module_id 
                                            from pat_pw_event_entry)
                                          )
                
                --FIM MID 4042 intake cannot be FIM goal rid 21
                and ((select rid 
                        from data_intake_responses
                       where intake_id = di.intake_id
                         and tid=1
                         and qid=1) != 21)                     
                
           order by di.complete_date asc
             )
       where rownum = 1; 
    
    end if;
    
    return v_nID;

exception
    when others then
    return null;  
end;

/*gets the value of the most recently answerd impairment q 
within the date range*/                   
function GetImpairmentRID(pi_vPatientID in varchar2,
                          pi_dtEnd in date)
  
 return number
 
 is
 
   v_nID number := null;
   
 begin
   
   select rid into v_nID
    from 
        ( select dir.rid 
           from data_intake_responses_audit dir 
           where dir.mid = 3000 
           and dir.tid=1
           and dir.qid=1
           and dir.patient_id = pi_vPatientID    
           and trunc(dir.complete_date) <= trunc(pi_dtEnd)
           order by dir.complete_date desc
         )
    where rownum=1;

    
    return v_nID;

exception
    when others then
    return null;  
end;

/*gets the value of the most recently answerd injury q 
within the date range*/
function GetInjuryRID(pi_vPatientID in varchar2,
                          pi_dtEnd in date)
  
 return number
 
 is
 
   v_nID number := null;
   
 begin
   
   select rid into v_nID
    from 
        ( select dir.rid 
           from data_intake_responses_audit dir 
           where dir.mid = 3000
           and dir.tid=1
           and dir.qid=4
           and dir.patient_id = pi_vPatientID    
           and trunc(dir.complete_date) <= trunc(pi_dtEnd)
           order by dir.complete_date desc
         )
    where rownum=1;
    
    return v_nID;

exception
    when others then
    return null;  
end;
                       

/*gets the discharge intake id,
only include intakes that have been reviewed*/
function GetDischargeIntakeID(pi_nMID in number,
                              pi_vPatientID in varchar2,
                              pi_dtStart in date,
                              pi_dtEnd in date)
  
 return number
 
 is
 
   v_nID number := null;
   
 begin
   
  --mid is not FIM, FIM is handled slightly different
   if pi_nMID != 4042 then 
  
     select intake_id into v_nID 
     from 
          (select di.intake_id 
             from data_intake di
            where di.patient_id = pi_vPatientID 
              and mid = pi_nMID 
              and trunc(di.complete_date) >= pi_dtStart
              and trunc(di.complete_date) <= pi_dtEnd
              
              --intake must be reviewed
              and di.intake_id in (select intake_id 
                                   from pat_pw_event_module em 
                                   where em.patient_id = pi_vPatientID 
                                     and em.pw_event_module_id 
                                     in (select pw_event_module_id 
                                          from pat_pw_event_entry)
                                        )
                                        
              and (select count(*) 
                   from data_intake di
                  where di.patient_id = pi_vPatientID 
                    and mid = pi_nMID 
                    and trunc(di.complete_date) >= pi_dtStart
                    and trunc(di.complete_date) <= pi_dtEnd 
                    
                    and di.intake_id in (select intake_id 
                                   from pat_pw_event_module em 
                                   where em.patient_id = pi_vPatientID 
                                     and em.pw_event_module_id 
                                     in (select pw_event_module_id 
                                          from pat_pw_event_entry)
                                        )
                    
                    ) > 1
               
         order by di.complete_date desc
           )
     where rownum = 1; 
     
    else
      
      select intake_id into v_nID 
     from 
          (select di.intake_id 
             from data_intake di
            where di.patient_id = pi_vPatientID 
              and mid = pi_nMID 
              and trunc(di.complete_date) >= pi_dtStart
              and trunc(di.complete_date) <= pi_dtEnd
              
              --intake must be reviewed
              and di.intake_id in (select intake_id 
                                   from pat_pw_event_module em 
                                   where em.patient_id = pi_vPatientID 
                                     and em.pw_event_module_id 
                                     in (select pw_event_module_id 
                                          from pat_pw_event_entry)
                                        )
                                        
              --FIM MID 4042 intake cannot be FIM goal rid 21
              and ((select rid 
                        from data_intake_responses
                       where intake_id = di.intake_id
                         and tid=1
                         and qid=1) != 21)   
              
              and (select count(*) 
                   from data_intake di
                  where di.patient_id = pi_vPatientID 
                    and mid = pi_nMID 
                    and trunc(di.complete_date) >= pi_dtStart
                    and trunc(di.complete_date) <= pi_dtEnd 
                    
                    and di.intake_id in (select intake_id 
                                   from pat_pw_event_module em 
                                   where em.patient_id = pi_vPatientID 
                                     and em.pw_event_module_id 
                                     in (select pw_event_module_id 
                                          from pat_pw_event_entry)
                                        )
                    
                    ) > 1
               
         order by di.complete_date desc
           )
     where rownum = 1; 
    
      
    end if;
    
    return v_nID;

exception
    when others then
    return null;  
end;

/*get the followup instrument id,
only include intakes that have been reviewed*/
function GetFollowupIntakeID(pi_nMID in number,
                             pi_vPatientID in varchar2,
                             pi_nDischargeID in number)
  
 return number
 
 is
 
   v_nID number := null;
   v_dtDischarge date := null;
   
 begin
   
   --get the discharge date
   select trunc(d.complete_date) into v_dtDischarge
   from data_intake d  
   where d.patient_id = pi_vPatientID
   and d.intake_id = pi_nDischargeID;
   
   --mid is not FIM, FIM is handled slightly different
   if pi_nMID != 4042 then 
  
     --get the first intake_id after the discharge date
     --call that followup
     select intake_id into v_nID 
     from 
          (select di.intake_id 
             from data_intake di
            where di.patient_id = pi_vPatientID 
              and mid = pi_nMID 
              and trunc(di.complete_date) > v_dtDischarge
              
              --FIM MID 4042 intake cannot be FIM goal rid 21
              and ((select rid 
                        from data_intake_responses
                       where intake_id = di.intake_id
                         and tid=1
                         and qid=1) != 21)  
                         
              --intake must be reviewed
              and di.intake_id in (select intake_id 
                                   from pat_pw_event_module em 
                                   where em.patient_id = pi_vPatientID 
                                     and em.pw_event_module_id 
                                     in (select pw_event_module_id 
                                          from pat_pw_event_entry)
                                        )
                                        
         order by di.complete_date asc
           )
     where rownum = 1; 
  
   else
     
     --get the first intake_id after the discharge date
     --call that followup
     select intake_id into v_nID 
     from 
          (select di.intake_id 
             from data_intake di
            where di.patient_id = pi_vPatientID 
              and mid = pi_nMID 
              and trunc(di.complete_date) > v_dtDischarge
              
              --intake cannot be FIM goal
              --FIM MID 4042 intake cannot be FIM goal rid 21
              and ((select rid 
                        from data_intake_responses
                       where intake_id = di.intake_id
                         and tid=1
                         and qid=1) != 21)  
                         
              --intake must be reviewed
              and di.intake_id in (select intake_id 
                                   from pat_pw_event_module em 
                                   where em.patient_id = pi_vPatientID 
                                     and em.pw_event_module_id 
                                     in (select pw_event_module_id 
                                          from pat_pw_event_entry)
                                        )
                                        
         order by di.complete_date asc
           )
     where rownum = 1; 
  
      
   end if;
    
   return v_nID;

exception
    when others then
    return null;  
end;

/*loads a temp table with population matching criteria*/
procedure LoadPopulation (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_dtFrom                 in date,      
      pi_dtTo                   in date,
      pi_nClinicalSetting       in number,
     
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_nCPAID                 in number,
      
      pi_nImpairmentID          in number,
      pi_nInjuryID              in number,
      pi_nGender                in number,
      pi_nMilStatusID           in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

     v_vSQL varchar2(4000) :=
      'insert into report_population(fx_user_id,
                                     patient_id,
                                     initial_date,
                                     end_date)
       select :UserID as fx_user_id,
              t.patient_id,
              t2.initial_date,
              t2.end_date
       from patient_demographics t,
            pat_treatment_program t2
       where t2.patient_id = t.patient_id
       
       and t2.end_date is not null
       and (      trunc(t2.end_date) >= trunc(:DTFROM)
              and trunc(t2.end_date) <= trunc(:DTEND)
            ) 
             
       ';
        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --delete current cached records for this user
    delete 
    from report_population t 
    where t.fx_user_id = pi_nUserID;
    commit;
    
    --execute the SQL
    EXECUTE IMMEDIATE v_vSQL
    USING pi_nUserID,
          pi_dtFrom,
          pi_dtTo;
         
    
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*get aggregate report given the module group id and mid
population:

pi_dtFrom, pi_dtTo - patients that 
have a pat_treatment initial_date and end_date
within this range (todo: need to look 
at pat_treatmet_programs?)

pi_nClinicalSetting - 1=outpatient, 2=inpatient
patients that have a pat_treatment, treatment_type_id 
matching the clinical setting passed in

region, site, cpa - pat_treatment_program

impairment - data_intake_responses mid 3000 qid 1

injury - data_intake_responses mid 3000 qid 4

gender - patient_demographics

duty status - patient_demographice

*/
procedure GetAggReportRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nModuleGroupID         in number,
      pi_nMID                   in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'select distinct MID,
                       SERIES,
                       DESCRIPTION,
                       null as ADMISSION,
                       null as DISCHARGE,
                       null as CHANGE1,
                       null as FOLLOWUP,
                       null as CHANGE2
                        
         from DATA_INTAKE_SCORE t
        where t.mid = :MID
         order by t.mid, t.series';
        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
      for v_vSQL
    using pi_nMID;
    commit;

    --clear any old data in the population module table
    --from this module
    delete from report_population_module t 
    where t.mid = pi_nMID
    and t.fx_user_id = pi_nUserID;
    commit;
    
    --create records for the mid
    insert into report_population_module(patient_id,
                                         fx_user_id,
                                         initial_date,
                                         end_date,
                                         mid,
                                         admission_intake_id,
                                         discharge_intake_id,
                                         followup_intake_id,
                                         los) 
    select patient_id,
           fx_user_id,
           initial_date,
           end_date,
           pi_nMID,
           null,
           null,
           null,
           null                  
    from report_population pp
    where pp.fx_user_id = pi_nUserID;
    
    commit;   

 --update report_population t 
    --  set t.mid = pi_nMID
    --where t.fx_user_id = pi_nUserID;
    --commit;
    
    --set the admission intake id
    update report_population_module ta
    set ta.admission_intake_id = GetAdmissionIntakeID(ta.mid,
                                                      ta.patient_id,
                                                      ta.initial_date,
                                                      ta.end_date)
         
    where ta.fx_user_id = pi_nUserID
      and ta.mid = pi_nMID;
    commit;                                                     
                      
    --set the discharge intake id
    update report_population_module td 
       set  td.discharge_intake_id = GetDischargeIntakeID(td.mid,
                                                          td.patient_id,
                                                          td.initial_date,
                                                          td.end_date)                                            
                                                     
                                                     
    where td.fx_user_id = pi_nUserID
    and td.mid = pi_nMID;
    commit;                           
        
    
    --set the followup intake id
    update report_population_module tf 
       set  tf.followup_intake_id = GetFollowupIntakeID(tf.mid,
                                                        tf.patient_id,
                                                        tf.discharge_intake_id)                                            
                                                     
                                                     
    where tf.fx_user_id = pi_nUserID
    and tf.mid = pi_nMID;
    commit;   
                               
            
    --now loop and do something to report_population
    --FOR rec IN (SELECT *
    --              FROM report_population t
    --             where t.fx_user_id = pi_nUserID) 
    --LOOP
    --
    --         null;
    --
    --
    --END LOOP;
    

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*get rs of injuries*/
procedure GetInjuryRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'select * from intake_response 
       where mid = 3000 and tid=1 and qid=4 
       order by mid,tid,qid,rid';
        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
      for v_vSQL;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*get rs of impairments*/
procedure GetImpairmentRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) :=
      'select * from intake_response 
       where mid = 3000 and tid=1 and qid=1 
       order by mid,tid,qid,rid';
        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
      for v_vSQL;
    commit;

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;



end PCK_REPORTS;
/

prompt
prompt Creating package body PCK_REPORTS_AGG
prompt =====================================
prompt
create or replace package body tbicds.PCK_REPORTS_AGG is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 
end PCK_REPORTS_AGG;
/

prompt
prompt Creating package body PCK_REPORTS_PAT
prompt =====================================
prompt
create or replace package body tbicds.PCK_REPORTS_PAT is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*Get previous intake score*/
function GetPrevIntakeScore(pi_nMID in number,
                            pi_vPatientID in varchar2,
                            pi_nIntakeID in number)
  
 return number
 
 is
 
   v_nScore number := 0;
   
 begin
   
   select score into v_nScore 
   from 
      (select s1.score   
         from data_intake_score s1,
              data_intake s2
        where s2.patient_id = s1.patient_id
          and s2.intake_id = s1.intake_id
          and s2.mid = s2.mid
            
          and s1.mid = pi_nMID
          and s1.patient_id = pi_vPatientID 
          and s1.series = 0 
          
          and s2.intake_id in (select intake_id 
                               from pat_pw_event_module aa,
                               pat_pw_event aaa
                               where aa.pat_pw_event_id = aaa.pat_pw_event_id
                               and aaa.status = 2
                               and ((select count(*)  
                                      from data_intake_responses
                                     where intake_id = aa.intake_id
                                       and mid = 4042 
                                       and tid=1
                                       and qid=1
                                       and rid=21) = 0) 
                               ) 
     
            
          and s2.complete_date < 
                     
          (select complete_date   
            from data_intake
           where patient_id = pi_vPatientID
             and intake_id = pi_nIntakeID
             and mid = pi_nMID 
             and rownum = 1 ) 
      order by s2.complete_date desc
      )where rownum = 1; 

    
    return v_nScore;

exception
    when others then
    return null;  
end;

/*Get current intake score*/
function GetCurrentIntakeScore(pi_vPatientID in varchar2,
                               pi_nMID in number)
  
 return number
 
 is
 
   v_nScore number := 0;
   
 begin
   
   select score into v_nScore 
   from 
       ( select score from (
        select tds.mid, di.complete_date, tds.score   
         from data_intake_score tds,
              data_intake di
        where tds.patient_id = pi_vPatientID
          and tds.mid = pi_nMID
          and tds.intake_id = di.intake_id
          and tds.series = 0 
          and di.intake_id in (select intake_id 
                               from pat_pw_event_module aa,
                               pat_pw_event aaa
                               where aa.pat_pw_event_id = aaa.pat_pw_event_id
                               and aaa.status = 2
                               
                               and ((select count(*)  
                                      from data_intake_responses
                                     where intake_id = aa.intake_id
                                       and mid = 4042 
                                       and tid=1
                                       and qid=1
                                       and rid=21) = 0) 
                               ) 
                               
        order by di.complete_date desc ))
        where rownum = 1;

    
    return v_nScore;

exception
    when others then
    return null;  
end;

/*Get note dates RS*/
procedure GetNoteDatesRS( pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vPatientID       in varchar2,
                          pi_dtFrom           in date,
                          pi_dtTo             in date,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor) 
is

strSQL       varchar2(4000) := '';

begin  
  

strSQL := 'select t.patient_id, 
                  t.pat_pw_event_id, 
                  t.tiu_date_submitted 
             from pat_pw_event t 
            where t.patient_id = :PATIENT_ID
              and t.status = 2 
              and (trunc(t.tiu_date_submitted) >= :FROM_DATE 
                   AND trunc(t.tiu_date_submitted) <= :TO_DATE)
         order by t.tiu_date_submitted desc';
  
    open rs 
    for strSQL
    using pi_vPatientID,
          pi_dtFrom,
          pi_dtTo;
    
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'Error retrieving notes';
  end;

/*Get note teext RS*/
procedure GetNoteTextRS( pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vPatientID       in varchar2,
                          pi_nPatPWEventID    in number,
                          pi_dtFrom           in date,
                          pi_dtTo             in date,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor) 
is

strSQL       varchar2(4000) := '';

begin  
  

strSQL := 'select t.note_text 
             from pat_pw_event t
            where t.patient_id = :PATIENT_ID
              and t.pat_pw_event_id = :PAT_PW_EVENT_ID 
              and t.status = 2 
              and (trunc(t.tiu_date_submitted) >= :FROM_DATE 
                   AND trunc(t.tiu_date_submitted) <= :TO_DATE)';
  
    open rs 
    for strSQL
    using pi_vPatientID,
          pi_nPatPWEventID,
          pi_dtFrom,
          pi_dtTo;
    
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'Error retrieving notes';
  end;

/*Get instrument score recordset*/
procedure GetInstrumentScoreRS( pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vPatientID       in varchar2,
                                pi_nMID             in number,
                                pi_dtFrom           in date,
                                pi_dtTo             in date,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor) 
is

--strSQL       varchar2(4000) := '';

begin  
  

/*strSQL := 'select t.patient_id, t.complete_date, 
          t.intake_id, t.mid, t3.module, t3.acronym, t2.score, 
          t2.interpretation 
  from data_intake t, data_intake_score t2, intake_module t3 
 where t.intake_id = t2.intake_id
   and t.mid = t3.mid 
   and t2.mid = t3.mid
   and t2.series = 0
   
   and t.intake_id in (select intake_id 
                         from pat_pw_event_module aa,
                              pat_pw_event aaa
                        where aa.pat_pw_event_id = aaa.pat_pw_event_id
                          and aaa.status = 2) 
       
   and t.intake_id in (select intake_id 
                       from data_intake_score 
                       where series=0)
   and t.mid = :MID
   and t.patient_id = :PATIENT_ID
   and (trunc(t.complete_date) >= :FROM_DATE 
              AND trunc(t.complete_date) <= :TO_DATE)
   order by t.complete_date desc';
  
    open rs 
    for strSQL
    using pi_nMID,
          pi_vPatientID,
          pi_dtFrom,
          pi_dtTo;
    */
   
    
 
 if pi_nMID != 4042 then 
   
   open rs for
    
    select t.patient_id, 
           t.intake_id, 
           t.mid, 
           t3.module,
           t3.acronym,
           t2.score, 
           t2.interpretation,
           evm.date_completed as complete_date,
           appu.name,
         
         --if mid = 4042 and rid=21 then this is a goal           
         (select count(*)  
            from data_intake_responses
           where intake_id = t.intake_id
             and mid = 4042 
             and tid=1
             and qid=1
             and rid=21) as is_goal
           
      from data_intake t, 
           data_intake_score t2, 
           intake_module t3,
           pat_pw_event_module evm,
           pat_pw_event ev, 
           fx_user fxu,
           app_user appu
           
     where t.intake_id = t2.intake_id
       and t.mid = t3.mid 
       and t2.mid = t3.mid
       and t2.series = 0 --SCORE
       and t.intake_id = evm.intake_id
       and evm.pat_pw_event_id = ev.pat_pw_event_id
       and ev.status = 2 --EVENT CLOSED
       and fxu.site_id = evm.site_id
       and fxu.fx_user_id = evm.completed_by
       and appu.fx_user_id = fxu.fx_user_id
       and t.mid = pi_nMID
       and t.patient_id = pi_vPatientID
       and (trunc(t.complete_date) >= pi_dtFrom 
                  AND trunc(t.complete_date) <= pi_dtTo)
       order by t.complete_date desc;
  
 else
   
   --EXCLUDE FIM GOAL from MID 4042
   open rs for
    select t.patient_id, 
           t.intake_id, 
           t.mid, 
           t3.module,
           t3.acronym,
           t2.score, 
           t2.interpretation,
           evm.date_completed as complete_date,
           appu.name,
       
       --if mid 4042 and rid=21 then this is a goal             
       (select count(*)  
          from data_intake_responses
         where intake_id = t.intake_id
           and mid = 4042 
           and tid=1
           and qid=1
           and rid=21) as is_goal
           
      from data_intake t, 
           data_intake_score t2, 
           intake_module t3,
           pat_pw_event_module evm,
           pat_pw_event ev, 
           fx_user fxu,
           app_user appu
           
     where t.intake_id = t2.intake_id
       and t.mid = t3.mid 
       and t2.mid = t3.mid
       and t2.series = 0 --SCORE
       and t.intake_id = evm.intake_id
       and evm.pat_pw_event_id = ev.pat_pw_event_id
       and ev.status = 2 --EVENT CLOSED
       and fxu.site_id = evm.site_id
       and fxu.fx_user_id = evm.completed_by
       and appu.fx_user_id = fxu.fx_user_id
       and t.mid = pi_nMID
       and t.patient_id = pi_vPatientID
       and (trunc(t.complete_date) >= pi_dtFrom 
                  AND trunc(t.complete_date) <= pi_dtTo)
       
       --exclude mid 4042 rid 21           
       and ( (select count(*)   
                from data_intake_responses 
               where intake_id = t.intake_id 
                 and mid=4042 
                 and tid=1 
                 and qid=1
                 and rid=21 ) < 1)
               
       order by t.complete_date desc;
  
  end if;
                 
    
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'Error retrieving scored instruments';
  end;
 
 /*Get trend base recordset*/  
 procedure GetTrendBaseRS( pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_vPatientID       in varchar2,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out RetRefCursor) 
is

strSQL       long := '';

begin  

strSQL := ' select t.patient_id, 
       t.pat_pw_id, 
       t.pat_pw_event_id, 
       t.pw_event_module_id, 
       t.mid,
       t.intake_id,
       t.date_completed,
       t2.module,
       
       (select count(*)  
            from data_intake_responses
           where intake_id = t.intake_id
             and mid = 4042 
             and tid=1
             and qid=1
             and rid=21) as is_goal, 
             
       (select es.event_severity_id  
          from pat_pw_event_entry pe,
               stat_event_severity es
          where pe.event_severity_id = es.event_severity_id 
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date = 
             (select max(event_date) 
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_severity_id,
            
           (select tds.interpretation   
              from data_intake_score tds
              where tds.patient_id = t.patient_id
              and tds.intake_id = t.intake_id
              and tds.patient_id = t.patient_id 
              and tds.mid = t.mid 
              and tds.series = 0
              and rownum=1) as current_interpretation,

           (select es.event_status 
          from pat_pw_event_entry pe,
               stat_event_status es
          where pe.event_status_id = es.event_status_id
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date = 
             (select max(event_date) 
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_status,              
      
          (select pe.event_status_id  
          from pat_pw_event_entry pe,
               stat_event_status es
          where pe.event_status_id = es.event_status_id
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date = 
             (select max(event_date) 
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_status_id,
            
         (select es.event_severity  
          from pat_pw_event_entry pe,
               stat_event_severity es
          where pe.event_severity_id = es.event_severity_id 
            and pe.patient_id = t.patient_id
            and pe.pw_event_module_id = t.pw_event_module_id
            and pe.event_date = 
             (select max(event_date) 
                from pat_pw_event_entry pe2
               where pe2.pw_event_module_id = t.pw_event_module_id)
            and rownum=1) as current_severity,
            
        (select nvl(tt.status, 0) 
             from pat_pw_event tt 
           where tt.pat_pw_event_id = t.pat_pw_event_id) 
           as event_status,
                     
       PCK_REPORTS_PAT.GetCurrentIntakeScore(t.patient_id, t.mid) as current_score,
       PCK_REPORTS_PAT.GetPrevIntakeScore(t.mid, t.patient_id, t.intake_id) as prev_score       

 from  PAT_PW_EVENT_MODULE t,
       intake_module t2
       
where  t.patient_id = :PAT_ID
       and t2.mid = t.mid 
       and t.status = 2 
       and nvl(t.intake_id,-1) > 0 
       and t.intake_id in (select intake_id 
                             from data_intake_score 
                            where series=0)
 
       and t.date_completed = (select max(x.date_completed) 
                                 from PAT_PW_EVENT_MODULE x, 
                                      pat_pw_event x2
                                 where x.mid = t2.mid
                                   and x.patient_id = t.patient_id
                                   and x.pat_pw_event_id = x2.pat_pw_event_id 
                                   and x2.status = 2
                                 
                                   and   (select count(*)  
                                          from data_intake_responses
                                         where intake_id = x.intake_id
                                           and mid = 4042 
                                           and tid=1
                                           and qid=1
                                           and rid=21) = 0 
                                 
                                 )
                                 
     order by t.date_completed desc';
  
    open rs 
    for strSQL
    using pi_vPatientID;
    
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'Error retrieving trend data';

  end; 
  
 
/*gets all scorable modules for this patient and date range
with the 10 most recent columns nulled out for fill in later*/
procedure GetInstrumentsBaseRS( pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vPatientID       in varchar2,
                                pi_dtFrom           in date,
                                pi_dtTo             in date,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor) 
is

strSQL       varchar2(4000) := '';

begin  

strSQL := 'select distinct(t.mid), 
                 case
                   when t3.acronym is null then 
                     case 
                       when length(t3.module) > 10 then trim(substr(t3.module,0,10)) || ''...''
                       else t3.module
                     end
                   else t3.acronym
                 end as short_name, 
                 t3.module, 
                 null as score_10,
                 null as score_9,
                 null as score_8,
                 null as score_7,
                 null as score_6,
                 null as score_5,
                 null as score_4,
                 null as score_3,
                 null as score_2,
                 null as score_1,
                 null as date_10,
                 null as date_9,
                 null as date_8,
                 null as date_7,
                 null as date_6,
                 null as date_5,
                 null as date_4,
                 null as date_3,
                 null as date_2,
                 null as date_1,
                 null as name_10,
                 null as name_9,
                 null as name_8,
                 null as name_7,
                 null as name_6,
                 null as name_5,
                 null as name_4,
                 null as name_3,
                 null as name_2,
                 null as name_1,
                 null as interpretation_10,
                 null as interpretation_9,
                 null as interpretation_8,
                 null as interpretation_7,
                 null as interpretation_6,
                 null as interpretation_5,
                 null as interpretation_4,
                 null as interpretation_3,
                 null as interpretation_2,
                 null as interpretation_1
            from data_intake t, data_intake_score t2, intake_module t3 
           where t.intake_id = t2.intake_id
             and t.mid = t3.mid 
             
              and t.intake_id in (select intake_id 
                         from pat_pw_event_module aa,
                              pat_pw_event aaa
                        where aa.pat_pw_event_id = aaa.pat_pw_event_id
                          and aaa.status = 2
                          
                          and ((select count(*)  
                                      from data_intake_responses
                                     where intake_id = aa.intake_id
                                       and mid = 4042 
                                       and tid=1
                                       and qid=1
                                       and rid=21) = 0) ) 
 

             and t.patient_id = :PATIENT_ID
              AND (trunc(t.complete_date) >= :FROM_DATE 
              AND trunc(t.complete_date) <= :TO_DATE)
             and t2.mid = t3.mid
             and t2.series = 0
             and t.intake_id in 
             (select intake_id from data_intake_score where series=0)
             order by short_name';
  
    open rs 
    for strSQL
    using pi_vPatientID,
          pi_dtFrom,
          pi_dtTo;
    
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'Error retrieving scored instruments';
  end;
             
  /*get a record set of all patients for the site*/
  procedure GetPatPopulationRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_vKey             in varchar2,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor) 
  is
  
    strSQL       varchar2(4000);
    
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    strSQL := 'select ';
    
    --patient id
    strSQL := strSQL || ' p.PATIENT_ID, ';
    
    --first name
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.FIRST_NAME, 
              :pi_vKey, p.PATIENT_ID) as first_name, ';
    
    --mi          
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.MI, 
              :pi_vKey, p.PATIENT_ID) as mi, ';
    
    --last name
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.LAST_NAME, 
              :pi_vKey, p.PATIENT_ID) as last_name, ';
              
    --full_name
    strSQL := strSQL || '( tbicds.fnc_utl_decstr(p.FIRST_NAME, 
                        :pi_vKey, p.PATIENT_ID) || '' '' || ' 
                        || ' tbicds.fnc_utl_decstr(p.MI, 
                        :pi_vKey, p.PATIENT_ID) || '' '' || ' 
                        || ' tbicds.fnc_utl_decstr(p.LAST_NAME,
                        :pi_vKey, p.PATIENT_ID)) as full_name, ';
    
    --gender          
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.GENDER, 
              :pi_vKey, p.PATIENT_ID) as gender, ';
    
    --dob          
    strSQL := strSQL || ' to_date(tbicds.fnc_utl_decstr(p.dob, 
              :pi_vKey, p.PATIENT_ID), ''MM/DD/YYYY'') as dob, ';
    
    --home phone  
    strSQL := strSQL || ' p.HOMEPHONE, ';
    
    --cell phone
    strSQL := strSQL || ' p.CELLPHONE, ';
    
    --work phone
    strSQL := strSQL || ' p.WORKPHONE, ';
    
    --email
    strSQL := strSQL || ' tbicds.fnc_utl_decstr(p.EMAIL, 
           :pi_vKey, p.PATIENT_ID) as email, ';
    
    --patient age
    strSQL := strSQL || ' trunc(months_between(SYSDATE, 
           to_date(tbicds.fnc_utl_decstr(p.dob, 
           :pi_vKey, p.PATIENT_ID), ''MM/DD/YYYY'')) / 12) 
           as patient_age ';
        
    strSQL := strSQL || ' from tbicds.patient_demographics p ';

    strSQL := strSQL || ' where ';
 
    --add only patients with events   
    strSQL := strSQL || '((select count(*) from pat_pw_event ppe ';
    strSQL := strSQL || ' where ppe.patient_id = p.patient_id) > 0) and ';
    
    --only patients with sites = users site     
    strSQL := strSQL || ' p.site_id in (';
        
    strSQL := strSQL || 'select site_id ';
    strSQL := strSQL || '  from tbicds.fx_user s ';
    strSQL := strSQL || ' where s.fx_user_id = :pi_nUserID ) ';
    
    strSQL := strSQL || ' order by 
              (tbicds.fnc_utl_decstr(p.LAST_NAME, 
              :pi_vKey, p.PATIENT_ID)) asc ';
  
  
    open rs for strSQL 
    using pi_vKey,
          pi_vKey,
          pi_vKey,
          pi_vKey,
          pi_vKey,
          pi_vKey,
          pi_vKey,
          pi_vKey,
          pi_vKey,
          pi_vKey,
          pi_nUserID,
          pi_vKey;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'Error retrieving population';
  end;


end PCK_REPORTS_PAT;
/

prompt
prompt Creating package body PCK_REPORTS_PI
prompt ====================================
prompt
create or replace package body tbicds.PCK_REPORTS_PI is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*
Get population module series recordset
*/
procedure GetPopModuleSeriesRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      
      pi_nSiteID                in number,
      pi_nMID                   in number,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) := '
      select distinct(series)  
      from report_population_module t,
           data_intake_score ds
      where t.fx_user_id = :USER_ID  
        and t.mid = :MID 
        and (t.site_id = :SITE_ID 
               or :SITE_ID = -1) 
            
       and( t.admission_intake_id = ds.intake_id 
         or t.discharge_intake_id = ds.intake_id
         or t.followup_intake_id = ds.intake_id)
      order by series';
        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
      for v_vSQL
    using pi_nUserID,
          pi_nMID,
          pi_nSiteID,
          pi_nSiteID;
          
    commit;
   

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*
Get populatuion module recordset
*/
procedure GetPopModuleRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vKey                   in varchar2,
   
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) := 'select t.*,
     
        tbicds.fnc_utl_decstr(t2.last_name, 
                            :KEY, 
                            t2.PATIENT_ID) as last_name,
                            
        tbicds.fnc_utl_decstr(t2.first_name, 
                            :KEY2, 
                            t2.PATIENT_ID) as first_name
                                     
         from REPORT_POPULATION_MODULE t,
              PATIENT_DEMOGRAPHICS t2
        where t.FX_USER_ID = :USERID
          and t2.patient_id = t.patient_id
         order by t.MID';
        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
      for v_vSQL
    using pi_vKey,
          pi_vKey,
          pi_nUserID;
    commit;
   

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*
Get population site recordset
*/
procedure GetPopSiteIDRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
     
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) := 'select distinct t.site_id 
                               from report_population t 
                               where t.fx_user_id = :USER_ID 
                               ';
        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
      for v_vSQL
    using pi_nUserID;
    commit;
   

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;

/*
Get population module recordset
*/
procedure GetPopMIDRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
     
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) := 'select distinct t.mid  
                               from report_population_module t 
                               where t.fx_user_id = :USER_ID 
                               ';
        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
      for v_vSQL
    using pi_nUserID;
    commit;
   

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;




/*gets population average scores*/
procedure GetPopScoreAvgRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) := 
'select s.site_name, m.module, 
        ds.mid, 
        t.site_id, 
        ds.series, 
        ds.description,
        round(avg(score),2) as average_score, 
        round(avg(los),2) as average_los,
        ''ADMISSION'' as score_type  
from report_population_module t,
     data_intake_score ds, 
     utl_site s, 
     intake_module m 
where t.admission_intake_id = ds.intake_id 
  and s.site_id = t.site_id 
  and m.mid = ds.mid 
  and t.fx_user_id = :UID1 
group by t.site_id, ds.mid, ds.series, ds.description, s.site_name, m.module 

union 

select  s.site_name, m.module, ds2.mid, t2.site_id, 
ds2.series, 
ds2.description,
round(avg(score),2) as average_score, 
round(avg(los),2) as average_los,
''DISCHARGE'' as score_type  
from report_population_module t2,
data_intake_score ds2,
 utl_site s, 
 intake_module m  
where t2.discharge_intake_id = ds2.intake_id
 and s.site_id = t2.site_id 
  and m.mid = ds2.mid 
and t2.fx_user_id = :UID2  
group by t2.site_id, ds2.mid, ds2.series, ds2.description, s.site_name, m.module 

union

select  s.site_name, m.module, ds3.mid, t3.site_id, 
ds3.series,
ds3.description,
round(avg(score),2) as average_score,
round(avg(los),2) as average_los, 
''FOLLOWUP'' as score_type  
from report_population_module t3,
data_intake_score ds3,
  utl_site s, 
     intake_module m 
where t3.followup_intake_id = ds3.intake_id
 and s.site_id = t3.site_id 
  and m.mid = ds3.mid 
and t3.fx_user_id = :UID3 
group by t3.site_id, ds3.mid, ds3.series, ds3.description, s.site_name, m.module 

order by  site_id, mid, series, score_type 
';

        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
      for v_vSQL
    using pi_nUserID,
          pi_nUserID,
          pi_nUserID;
    commit;
   

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*gets population scores for all sites*/
procedure GetPopScoreAvgALLRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nExcludeSiteID         in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) := 
'select ds.mid, 
        ''All'' as site_name, 
        m.module,  
        -1 as site_id, 
        ds.series, 
        ds.description,
        round(avg(score),2) as average_score, 
        round(avg(los),2) as average_los,
        ''ADMISSION'' as score_type  
from report_population_module t,
data_intake_score ds,
     intake_module m 
where t.admission_intake_id = ds.intake_id
  and m.mid = ds.mid 
and t.fx_user_id = :UID1 
and t.site_id != :ExcludeSiteID
group by ds.mid, ds.series, ds.description, m.module 

union 

select ds2.mid, 
       ''All'' as site_name, 
       m.module,      
       -1 as site_id,    
ds2.series, 
ds2.description,
round(avg(score),2) as average_score, 
round(avg(los),2) as average_los,
''DISCHARGE'' as score_type  
from report_population_module t2,
data_intake_score ds2,
     intake_module m 
where t2.discharge_intake_id = ds2.intake_id
  and m.mid = ds2.mid 
and t2.fx_user_id = :UID2 
and t2.site_id <> :ExcludeSiteID 
group by ds2.mid, ds2.series, ds2.description, m.module 

union

select ds3.mid, 
       ''All'' as site_name, 
       m.module,
       -1 as site_id, 
ds3.series,
ds3.description,
round(avg(score),2) as average_score,
round(avg(los),2) as average_los, 
''FOLLOWUP'' as score_type  
from report_population_module t3,
data_intake_score ds3,
     intake_module m 
where t3.followup_intake_id = ds3.intake_id
  and m.mid = ds3.mid 
and t3.fx_user_id = :UID3 
and t3.site_id != :ExcludeSiteID
group by ds3.mid, ds3.series, ds3.description, m.module 

order by  mid, series, score_type 
';

        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
      for v_vSQL
    using pi_nUserID,
          pi_nExcludeSiteID,
          pi_nUserID,
          pi_nExcludeSiteID,
          pi_nUserID,
          pi_nExcludeSiteID;
    commit;
   

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*gets population scores*/
procedure GetPopScoreRS (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vKey                   in varchar2,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2,
      rs                        out RetRefCursor
      )
is

     v_vSQL varchar2(4000) := '

select * from (         
select t.site_id, ds.*, ''ADMISSION'' as score_type, 

   tbicds.fnc_utl_decstr(p.last_name, 
                            :KEY, 
                            p.PATIENT_ID) as last_name,
                            
   tbicds.fnc_utl_decstr(p.first_name, 
                            :KEY2, 
                            p.PATIENT_ID) as first_name
  
from report_population_module t,
data_intake_score ds,
patient_demographics p
where t.admission_intake_id = ds.intake_id 
and t.patient_id = p.patient_id 
and t.fx_user_id = :UID1

union

select t2.site_id, ds2.*, ''DISCHARGE'' as score_type, 

   tbicds.fnc_utl_decstr(p.last_name, 
                            :KEY, 
                            p.PATIENT_ID) as last_name,
                            
   tbicds.fnc_utl_decstr(p.first_name, 
                            :KEY2, 
                            p.PATIENT_ID) as first_name
   
from report_population_module t2,
data_intake_score ds2,
patient_demographics p
where t2.discharge_intake_id = ds2.intake_id
and t2.patient_id = p.patient_id 
and t2.fx_user_id = :UID2


union

select t3.site_id, ds3.*, ''FOLLOWUP'' as score_type, 

   tbicds.fnc_utl_decstr(p.last_name, 
                            :KEY, 
                            p.PATIENT_ID) as last_name,
                            
   tbicds.fnc_utl_decstr(p.first_name, 
                            :KEY2, 
                            p.PATIENT_ID) as first_name
   
from report_population_module t3,
data_intake_score ds3,
patient_demographics p
where t3.followup_intake_id = ds3.intake_id 
and t3.patient_id = p.patient_id 
and t3.fx_user_id = :UID3
)
order by site_id, mid, series';

        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --open the result set
    open rs 
      for v_vSQL
    using
          pi_vKey, 
          pi_vKey,
          pi_nUserID,
          
          pi_vKey, 
          pi_vKey,
          pi_nUserID,
          
          pi_vKey, 
          pi_vKey,
          pi_nUserID;
    commit;
   

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*loads module data to the temp table*/
procedure LoadPopModule (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nMID                   in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --clear any old data in the population module table
    --from this module
    delete from report_population_module t 
    where t.mid = pi_nMID
      and t.fx_user_id = pi_nUserID;
    commit;
    
    --create records for the mid
    insert into report_population_module(patient_id,
                                         fx_user_id,
                                         initial_date,
                                         end_date,
                                         mid,
                                         admission_intake_id,
                                         discharge_intake_id,
                                         followup_intake_id,
                                         los,
                                         site_id) 
    select patient_id,
           fx_user_id,
           initial_date,
           end_date,
           pi_nMID,
           null,
           null,
           null,
           --null,
           --NUMTODSINTERVAL(end_date - initial_date, 'DAY'),
           trunc(end_date - initial_date),
           site_id                   
    from report_population pp
    where pp.fx_user_id = pi_nUserID;
    
    commit;   

    --set the admission intake id
    update report_population_module ta
    set ta.admission_intake_id = PCK_REPORTS.GetAdmissionIntakeID(ta.mid,
                                                      ta.patient_id,
                                                      ta.initial_date,
                                                      ta.end_date)
         
    where ta.fx_user_id = pi_nUserID
      and ta.mid = pi_nMID;
    commit;                                                     
                      
    --set the discharge intake id
    update report_population_module td 
       set  td.discharge_intake_id = PCK_REPORTS.GetDischargeIntakeID(td.mid,
                                                          td.patient_id,
                                                          td.initial_date,
                                                          td.end_date)                                            
                                                     
                                                     
    where td.fx_user_id = pi_nUserID
    and td.mid = pi_nMID;
    commit;                           
        
    
    --set the followup intake id
    update report_population_module tf 
       set  tf.followup_intake_id = PCK_REPORTS.GetFollowupIntakeID(tf.mid,
                                                        tf.patient_id,
                                                        tf.discharge_intake_id)                                            
                                                     
                                                     
    where tf.fx_user_id = pi_nUserID
    and tf.mid = pi_nMID;
    commit;   
                               
            
    --now loop and do something to report_population
    --FOR rec IN (SELECT *
    --              FROM report_population t
    --             where t.fx_user_id = pi_nUserID) 
    --LOOP
    --
    --         null;
    --
    --
    --END LOOP;
    

exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
      
end;


/*loads a temp table with population matching criteria*/
procedure LoadPopulation (
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_vKey                   in varchar2,
      
      pi_dtFrom                 in date,      
      pi_dtTo                   in date,
      pi_nClinicalSetting       in number,
     
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_nCPATypeID             in number, --type
      
      pi_nImpairmentID          in number,
      pi_nInjuryID              in number,
      pi_vGender                in varchar2,
      pi_nMilStatusID           in number,
      pi_vSiteIDS               in varchar2,
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2
      )
is

     v_vSQL varchar2(4000) :=
      'insert into report_population(fx_user_id,
                                     patient_id,
                                     initial_date,
                                     end_date,
                                     site_id)
       select :UserID as fx_user_id,
              t.patient_id,
              t2.initial_date,
              t2.end_date,
              t.site_id
       from patient_demographics t,
            pat_treatment_program t2,
            pat_treatment t3
       where t2.patient_id = t.patient_id
       and t2.treatment_id = t3.treatment_id 
       and ( (:GENDER = ''-1'')
             or 
             ( tbicds.fnc_utl_decstr(t.gender, 
                                     :KEY, 
                                     t.PATIENT_ID) = :GENDER2
              )
            )
       
       and ( (:SITES = ''-1'')
             or
             ( 
               instr(:MATCH_SITES, '','' || t.site_id || '','' ) > 0
              )
            )

       and t2.end_date is not null
       and (      trunc(t2.end_date) >= trunc(:DTFROM)
              and trunc(t2.end_date) <= trunc(:DTEND)
              and ( (:CLINSETT = -1)
                      or
                    (t3.treatment_type_id = :CLINSETT2)
                   )
              
               and ( (:CPA_TYPE = ''-1'')
                   or
                   ( 
                      :CPA_TYPE2 = 
                         (select cpa_type_id  
                            from cpa cp  
                           where cp.cpa_id = t2.cpa_id )
                    )
                  ) 
              
              
              
            ) 
            
        and ( (:IMPAIRMENT1 = -1)
                or
                (
                  :IMPAIRMENT2 = PCK_REPORTS.GetImpairmentRID(t.patient_id, t2.end_date)                
                )
             )

       and ( (:INJURY1 = -1)
                or
                (
                  :INJURY2 = PCK_REPORTS.GetInjuryRID(t.patient_id, t2.end_date)                
                )
             )      
             
       and ( (:DUTYSTATUS1 = -1)
                or
                (
                  :DUTYSTATUS2 = t.duty_status_id                 
                )
             )           
       ';
        
begin

    po_nStatusCode    := 0;
    po_vStatusComment := '';
    
    --delete current cached records for this user
    delete 
    from report_population t 
    where t.fx_user_id = pi_nUserID;
    commit;
    
    delete from report_population_module tm
    where tm.fx_user_id = pi_nUserID;
    commit;
    
    
    --execute the SQL
    EXECUTE IMMEDIATE v_vSQL
    USING pi_nUserID,
          pi_vGender,
          pi_vKey,
          pi_vGender,
          pi_vSiteIDS,
          pi_vSiteIDS,
          pi_dtFrom,
          pi_dtTo,
          pi_nClinicalSetting,
          pi_nClinicalSetting,
          pi_nCPATypeID,
          pi_nCPATypeID,
          pi_nImpairmentID,
          pi_nImpairmentID,
          --pi_dtTo,
          pi_nInjuryID,
          pi_nInjuryID,
          --pi_dtTo,
          pi_nMilStatusID,
          pi_nMilStatusID;
         
    
    commit;

--exception
  --  when others then
    --  po_nStatusCode    := 1;
     -- po_vStatusComment := '';
      
end;


end PCK_REPORTS_PI;
/

prompt
prompt Creating package body PCK_REPORTS_STAT
prompt ======================================
prompt
create or replace package body tbicds.PCK_REPORTS_STAT is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  /*
  Create a new export request.
  */
  procedure CreateExportRequestRS(pi_vSessionID         in varchar2,
                                  pi_vSessionClientIP   in varchar2,
                                  pi_nUserID            in number,
                                  pi_vExportRequestName in varchar2,
                                  po_nStatusCode        out number,
                                  po_vStatusComment     out varchar2,
                                  rs                    out RetRefCursor)
  is

    v_seqRequestID   number;
    v_nRptNameExists number := 0;

  begin

    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    begin
      select count(*)
        into v_nRptNameExists
        from exp_statistical_rpt t
       where t.fx_user_id = pi_nUserID
         and t.report_name = pi_vExportRequestName;
    end;

    if v_nRptNameExists = 0 then
      --get a new request id
      select seqexpstatisticalrpt.nextval into v_seqRequestID from dual;

      --create the export request record...
      insert into exp_statistical_rpt(request_id,fx_user_id,report_name,status)
      values(
        v_seqRequestID,
        pi_nUserID,
        pi_vExportRequestName,
        0 --new request pending for definition
      );
      commit;
      
      open rs for
        select v_seqRequestID as REQUEST_ID from dual;
    else
      --raise exception
      po_nStatusCode    := 2;
      po_vStatusComment := 'Export request already exists.';
    end if;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_REPORTS_STAT.CreateExportRequest(): ' || sqlErrm;
  end;

  /*
  Get a list of the request of this user.
  */
  procedure GetMyRequestRS(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out RetRefCursor)
  is

  begin

    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    open rs for
      select
        t.request_id,
        t.report_name,
        t.status as status_code,
        case t.status
          when -1 then 'Error'
          when  0 then 'New (Pending for Execution)'
          when  1 then 'In Progress'
          when  2 then 'Ready for Download'
          when  3 then 'Canceled' 
        end as status_description,
        t.start_date as str_date,
        t.end_date as end_date
      from exp_statistical_rpt t
      where t.fx_user_id = pi_nUserID
      order by t.request_id desc;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_REPORTS_STAT.GetMyRequestRS(): ' || sqlErrm;
  end;

  /*
  Rename export request
  */
  procedure RenameExportRequest(pi_vSessionID            in varchar2,
                                pi_vSessionClientIP      in varchar2,
                                pi_nUserID               in number,
                                pi_nRequestID            in number,
                                pi_vNewExportRequestName in varchar2,
                                po_nStatusCode           out number,
                                po_vStatusComment        out varchar2)
  is

    v_nRptNameExists number := 0;
    v_nTargetExists  number := 0;

  begin

    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    --val 1: new export request name already exists?
    begin
      select count(*)
        into v_nRptNameExists
        from exp_statistical_rpt t
       where t.fx_user_id = pi_nUserID
         and t.report_name = pi_vNewExportRequestName;
    end;

    if v_nRptNameExists = 0 then
      --val 2: target request to be rename, exists?
      begin
        select count(*)
          into v_nTargetExists
          from exp_statistical_rpt t
         where t.fx_user_id = pi_nUserID
           and t.request_id = pi_nRequestID;
        end;

        if v_nTargetExists = 0 then
          --raise exception
          po_nStatusCode    := 3;
          po_vStatusComment := 'Export request not found.';

        else
          --rename
          update exp_statistical_rpt set
            report_name = pi_vNewExportRequestName
          where fx_user_id = pi_nUserID
            and request_id = pi_nRequestID;
          commit;
        end if;
    else
      --raise exception
      po_nStatusCode    := 2;
      po_vStatusComment := 'Export request already exists.';
    end if;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_REPORTS_STAT.RenameExportRequest(): ' || sqlErrm;
  end;

  /*
  Update export request
  */
  procedure UpdateExportRequest(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nRequestID       in number,
                                pi_vFilters         in varchar2,
                                pi_vDataFields      in varchar2,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2)
  is

    v_nTargetExists  number := 0;

  begin

    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    --val 1: target request exists?
    begin
      select count(*)
        into v_nTargetExists
        from exp_statistical_rpt t
       where t.fx_user_id = pi_nUserID
         and t.request_id = pi_nRequestID
         and t.status = 0; --Only New request can be updated
    end;

    if v_nTargetExists = 1 then
      --update filters and datafields
        update exp_statistical_rpt set
          filters = pi_vFilters,
          data_included = pi_vDataFields
        where fx_user_id = pi_nUserID
          and request_id = pi_nRequestID
          and status = 0; --Only New request can be updated
        commit;
    else
      --raise exception
      if v_nTargetExists = 0 then
        po_nStatusCode    := 2;
        po_vStatusComment := 'Request not found.';
      else
        po_nStatusCode    := 3;
        po_vStatusComment := 'Multiple request found with the same request ID.'; --this won't happend because it will be a primary key violation.
      end if;
    end if;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_REPORTS_STAT.UpdateExportRequest(): ' || sqlErrm;
  end;

  /*
  Get export request recordset
  */
  procedure GetExportRequestRS(pi_vSessionID       in varchar2,
                               pi_vSessionClientIP in varchar2,
                               pi_nUserID          in number,
                               pi_nRequestID       in number,
                               po_nStatusCode      out number,
                               po_vStatusComment   out varchar2,
                               rs                  out RetRefCursor)
  is

    v_nTargetExists  number := 0;

  begin

    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    --val 1: target request exists?
    begin
      select count(*)
        into v_nTargetExists
        from exp_statistical_rpt t
       where t.fx_user_id = pi_nUserID
         and t.request_id = pi_nRequestID;
    end;

    if v_nTargetExists = 1 then
      open rs for
        select t.report_name,
               t.filters,
               t.data_included
          from exp_statistical_rpt t
         where t.fx_user_id = pi_nUserID
           and t.request_id = pi_nRequestID;
    else
      --raise exception
      if v_nTargetExists = 0 then
        po_nStatusCode    := 2;
        po_vStatusComment := 'Request not found.';
      else
        po_nStatusCode    := 3;
        po_vStatusComment := 'Multiple request found with the same request ID.'; --this won't happend because it will be a primary key violation.
      end if;
    end if;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_REPORTS_STAT.GetExportRequestRS(): ' || sqlErrm;
  end;

  /*
  Save export request
  */
  procedure SaveAsExportRequest(pi_vSessionID         in varchar2,
                                pi_vSessionClientIP   in varchar2,
                                pi_nUserID            in number,
                                pi_vExportRequestName in varchar2,
                                pi_vFilters         in varchar2,
                                pi_vDataFields      in varchar2,
                                po_nStatusCode        out number,
                                po_vStatusComment     out varchar2)
  is

    v_seqRequestID   number;
    v_nRptNameExists number := 0;

  begin

    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    --val 1: target request exists?
    begin
      select count(*)
        into v_nRptNameExists
        from exp_statistical_rpt t
       where t.fx_user_id = pi_nUserID
         and t.report_name = pi_vExportRequestName;
    end;

    if v_nRptNameExists = 0 then
      --get a new request id
      select seqexpstatisticalrpt.nextval into v_seqRequestID from dual;

      --create the export request record...
      insert into exp_statistical_rpt(request_id,fx_user_id,report_name,status,filters,data_included)
      values(
        v_seqRequestID,
        pi_nUserID,
        pi_vExportRequestName,
        0, --new request pending for definition
        pi_vFilters,
        pi_vDataFields
      );
      commit;
    else
      --raise exception
      po_nStatusCode    := 2;
      po_vStatusComment := 'Export request already exists.';
    end if;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_REPORTS_STAT.SaveAsExportRequest(): ' || sqlErrm;
  end;
  
  /*
  Submit export request
  */
  procedure SubmitExportRequest(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_vKey             in varchar2,
                                pi_nRequestID       in number,
                                pi_vFilters         in varchar2,
                                pi_vDataFields      in varchar2,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2)
  is

    v_nTargetExists  number := 0;

  begin

    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    --val 1: target request exists?
    begin
      select count(*)
        into v_nTargetExists
        from exp_statistical_rpt t
       where t.fx_user_id = pi_nUserID
         and t.request_id = pi_nRequestID
         and t.status = 0; --Only New request can be updated
    end;

    if v_nTargetExists = 1 then
      --update filters, datafields, status, and start_date
        update exp_statistical_rpt set
          filters = pi_vFilters,
          data_included = pi_vDataFields,
          status = 1, --In Progress
          start_date = sysdate
        where fx_user_id = pi_nUserID
          and request_id = pi_nRequestID
          and status = 0; --Only New request can be updated
        commit;
        
        --CALL CSV BUILDER PROCESS
        PCK_UTL_EXPORT_DATA.runExport (
          pi_vSessionID,
          pi_vSessionClientIP,
          pi_nUserID,
          pi_nRequestID,
          pi_vKey,
          po_nStatusCode,
          po_vStatusComment
        );

    else
      --raise exception
      if v_nTargetExists = 0 then
        po_nStatusCode    := 2;
        po_vStatusComment := 'Request not found.';
      else
        po_nStatusCode    := 3;
        po_vStatusComment := 'Multiple request found with the same request ID.'; --this won't happend because it will be a primary key violation.
      end if;
    end if;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_REPORTS_STAT.SubmitExportRequest(): ' || sqlErrm;
  end;
  
  /*
  Cancel export request
  */
  procedure CancelExportRequest(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nRequestID       in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2)
  is

    v_nTargetExists  number := 0;

  begin

    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    --val 1: target request exists?
    begin
      select count(*)
        into v_nTargetExists
        from exp_statistical_rpt t
       where t.fx_user_id = pi_nUserID
         and t.request_id = pi_nRequestID
         and t.status = 1; --Only In Progress request can be cancel
    end;

    if v_nTargetExists = 1 then
      --update status and end_date
        update exp_statistical_rpt set
          status = 3, --Canceled
          end_date = sysdate
        where fx_user_id = pi_nUserID
          and request_id = pi_nRequestID
          and status = 1; --Only In Progress request can be cancel
        commit;
        
        --STOP CSV BUILDER PROCESS???
        PCK_UTL_EXPORT_DATA.cancelExport (
          pi_vSessionID,
          pi_vSessionClientIP,
          pi_nUserID,
          pi_nRequestID,
          po_nStatusCode,
          po_vStatusComment
        );

    else
      --raise exception
      if v_nTargetExists = 0 then
        po_nStatusCode    := 2;
        po_vStatusComment := 'Request not found.';
      else
        po_nStatusCode    := 3;
        po_vStatusComment := 'Multiple request found with the same request ID.'; --this won't happend because it will be a primary key violation.
      end if;
    end if;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_REPORTS_STAT.CancelExportRequest(): ' || sqlErrm;
  end;
  
  /*
  Get export request CSV
  */
  procedure GetExportRequestCSVFileRS(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      pi_nRequestID       in number,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2,
                                      rs                  out RetRefCursor)
  is

    v_nTargetExists  number := 0;

  begin

    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    --val 1: target request exists?
    begin
      select count(*)
        into v_nTargetExists
        from exp_statistical_rpt t
       where t.fx_user_id = pi_nUserID
         and t.request_id = pi_nRequestID
         and t.status = 2;
    end;

    if v_nTargetExists = 1 then
      open rs for
        select t.report_name,
               t.file_data
          from exp_statistical_rpt t
         where t.fx_user_id = pi_nUserID
           and t.request_id = pi_nRequestID
           and t.status = 2;
           
      --AUDIT
      insert into exp_statistical_rpt_audit(request_id,fx_user_id,request_download_date) 
      values(pi_nRequestID,
             pi_nUserID,
             sysdate);
      commit;
      
    else
      --raise exception
      if v_nTargetExists = 0 then
        po_nStatusCode    := 2;
        po_vStatusComment := 'Request not found.';
      else
        po_nStatusCode    := 3;
        po_vStatusComment := 'Multiple request found with the same request ID.'; --this won't happend because it will be a primary key violation.
      end if;
    end if;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_REPORTS_STAT.GetExportRequestCSVFileRS(): ' || sqlErrm;
  end;
  
  /*
  Submit new export request
  */
  procedure SubmitNewExportRequest(pi_vSessionID         in varchar2,
                                   pi_vSessionClientIP   in varchar2,
                                   pi_nUserID            in number,
                                   pi_vKey               in varchar2,
                                   pi_vExportRequestName in varchar2,
                                   pi_vFilters           in varchar2,
                                   pi_vDataFields        in varchar2,
                                   po_nStatusCode        out number,
                                   po_vStatusComment     out varchar2)
  is

    v_seqRequestID   number;
    v_nRptNameExists number := 0;

  begin

    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';

    begin
      select count(*)
        into v_nRptNameExists
        from exp_statistical_rpt t
       where t.fx_user_id = pi_nUserID
         and t.report_name = pi_vExportRequestName;
    end;

    if v_nRptNameExists = 0 then
      --get a new request id
      select seqexpstatisticalrpt.nextval into v_seqRequestID from dual;

      --create the export request record...
      insert into exp_statistical_rpt(request_id,fx_user_id,report_name,filters,data_included,status,start_date)
      values(
        v_seqRequestID,
        pi_nUserID,
        pi_vExportRequestName,
        pi_vFilters,
        pi_vDataFields,
        1, --In Progress
        sysdate
      );
      commit;
      
      --CALL CSV BUILDER PROCESS
      PCK_UTL_EXPORT_DATA.runExport (
        pi_vSessionID,
        pi_vSessionClientIP,
        pi_nUserID,
        v_seqRequestID,
        pi_vKey,
        po_nStatusCode,
        po_vStatusComment
      );
      
    else
      --raise exception
      po_nStatusCode    := 2;
      po_vStatusComment := 'Export request already exists.';
    end if;

  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := 'PCK_REPORTS_STAT.SubmitNewExportRequest(): ' || sqlErrm;
  end;

end PCK_REPORTS_STAT;
/

prompt
prompt Creating package body PCK_RPT_CDE
prompt =================================
prompt
create or replace package body tbicds.PCK_RPT_CDE is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   /*get Patient Cde Value*/
   procedure getPatientCdeValue (
      pi_vPatientID                     in varchar2,
      pi_vCdeID                         in varchar2,
      pi_nIntakeID                      in number,
      pi_vKey                           in varchar2,
      po_vValue                        out varchar2
      )
   is
      v_vSql                               varchar2(4000);
      rd                                   cde_stat_map%rowtype;
      v_vValue                             varchar2(128);
   begin
      v_vSql := 'select * from cde_stat_map where cde_id = :P0';
      execute immediate v_vSql into rd using pi_vCdeID;
   
      -- case: cde map type = Question
      if (rd.cde_map_type_id = 1)
         or (rd.cde_map_type_id = 3)
         or (rd.cde_map_type_id = 5)
      then
         v_vSql := 'select t.'||rd.field_name||' '
                   ||'from '||rd.table_name||' t '
                   ||'where t.patient_id = :P0 '
                   ||'and t.intake_id = :P1 '
                   ||'and t.mid = :P2 '
                   ||'and t.tid = :P3 '
                   ||'and t.qid = :P4 '
                   ||'and t.rid in (select s.rid from intake_response s where s.mid = t.mid and s.tid = t.tid and s.qid = t.qid) '
                   ||'and rownum = 1 ';
         execute immediate v_vSql into v_vValue using pi_vPatientID, pi_nIntakeID, rd.intake_mid, rd.intake_tid, rd.intake_qid;

      -- case: cde map type = Response
      elsif (rd.cde_map_type_id = 2)
      then
         null;
         
      -- case: cde map type = Score
      elsif (rd.cde_map_type_id = 3)
      then
         null;
         
      -- case: cde map type = Table
      elsif (rd.cde_map_type_id = 4)
      then
         if (instr(','||c_vEncrytedCdeIDs||',', ','||pi_vCdeID||',') > 0)
         then
            v_vSql := 'select '||rd.field_name||' from '||rd.table_name||' where patient_id = :P0';
            execute immediate v_vSql into v_vValue using pi_vPatientID;
            v_vValue := tbicds.ic_utl_sec.decryptdata (v_vValue, pi_vKey, pi_vPatientID);

            --? need to verify
            --if (rd.field_name like 'GENDER')
            --then
            --   v_vSql := 'select item from stat_data_collection where collection_type = :P0 and collection_item_id = :P1';
            --   execute immediate v_vSql into v_vValue using '_GENDER', v_vValue;*\
            --end if;
            
         else
            v_vSql := 'select wm_concat(s.item) '
                      ||'from '||rd.table_name||' t, stat_data_collection s '
                      ||'where t.patient_id = :P0 '
                      ||'and s.collection_type = :P1 '
                      ||'and t.'||rd.field_name||' = s.collection_item_id ';
            execute immediate v_vSql into v_vValue using pi_vPatientID, '_'||replace(rd.field_name, '_ID');
            
         end if;

      -- case: cde map type = Scale
      elsif (rd.cde_map_type_id = 5)
      then
         null;
         
      end if;
      
      po_vValue := v_vValue;
      
   exception
      when others 
      then 
         null;
   end;
      
   /*set Patient Cde: exclude encrypted demographic data */
   procedure setPatientCde (
      pi_vPatientID                     in varchar2 default null
      )
   is
      v_vSql                               varchar2(32767);
      rc1                                  sys_refcursor;
      rc2                                  sys_refcursor;
      rd                                   typ_obj_rpt_cde_pat;
      v_nIndex                             number;
      v_vPatientID                         varchar2(50);
      v_vCdeID                             varchar2(30);
      v_nIntakeID                          number(5);
      v_vValue                             varchar2(128);
   begin
      rd := typ_obj_rpt_cde_pat();
      
      -- part 1: add patient with intake data
      v_vSql := 'select distinct t.patient_id, t.intake_id from data_intake t '
                ||'where complete = 1'
                ||'and not exists (select * from patient_cde_rpt s where s.patient_id = t.patient_id and s.intake_id = t.intake_id) '
                ||case when (pi_vPatientID is not null) then 'and t.patient_id = '''||pi_vPatientID||''' ' end;
      open rc1 for v_vSql;
      loop
         fetch rc1 into v_vPatientID, v_nIntakeID;
         exit when rc1%notfound;
         v_nIndex := 0;
         
         begin
            --v_vSql := 'delete from patient_cde_rpt where patient_id = :P0 and intake_id = :P1';
            --execute immediate v_vSql using v_vPatientID, v_nIntakeID;
            
            v_vSql := 'select cde_id from cde_stat_map order by cde_id';
            open rc2 for v_vSql;
            loop
               fetch rc2 into v_vCdeID;
               exit when rc2%notfound;
               v_nIndex := v_nIndex + 1;
               
               -- exclude encrypted demographic data
               if (instr(','||c_vEncrytedCdeIDs||',', ','||v_vCdeID||',') = 0)
               then
                  getPatientCdeValue (v_vPatientID, v_vCdeID, v_nIntakeID, null, v_vValue);
                  rd.setValue(v_nIndex, v_vValue);
               end if;
            end loop;
            close rc2;
                   
            v_vSql := 'insert into patient_cde_rpt values (:P0, :P1, :P2, :P3)';
            execute immediate v_vSql using v_vPatientID, v_nIntakeID, sysdate, rd;
            commit;
            
         --exception
           -- when others
           -- then
             --  rollback;
         end;
      end loop;
      close rc1;

      -- part 2 (optional): add patient with no intake data
      v_vSql := 'select t.patient_id from patient_demographics t '
                ||'where 1 = '||c_nIncludeNoIntake||' '
                ||'and not exists (select * from patient_cde_rpt s where s.patient_id = t.patient_id) '
                ||case when (pi_vPatientID is not null) then 'and t.patient_id = '''||pi_vPatientID||''' ' end;
      open rc1 for v_vSql;
      loop
         fetch rc1 into v_vPatientID;
         exit when rc1%notfound;
         v_nIndex := 0;
         
         begin
            v_vSql := 'delete from patient_cde_rpt where patient_id = :P0';
            execute immediate v_vSql using v_vPatientID;
            
            v_vSql := 'select cde_id from cde_stat_map order by cde_id';
            open rc2 for v_vSql;
            loop
               fetch rc2 into v_vCdeID;
               exit when rc2%notfound;
               v_nIndex := v_nIndex + 1;
               
               -- exclude encrypted demographic data
               if (instr(','||c_vEncrytedCdeIDs||',', ','||v_vCdeID||',') = 0)
               then
                  getPatientCdeValue (v_vPatientID, v_vCdeID, null, null, v_vValue);
                  rd.setValue(v_nIndex, v_vValue);
               end if;
            end loop;
            close rc2;
                   
            v_vSql := 'insert into patient_cde_rpt values (:P0, :P1, :P2, :P3)';
            execute immediate v_vSql using v_vPatientID, -1, sysdate, rd;
            commit;
            
         exception
            when others
            then
               rollback;
         end;
      end loop;
      close rc1;      
   end;
      
   /*tabel Patient Cde */
   function tblPatientCde (
      pi_vKey                           in varchar2,
      pi_vProviderID                    in varchar2,
      pi_dDateRange_Start               in date,
      pi_dDateRange_End                 in date
      ) return                             typ_tbl_rpt_cde_pat pipelined
   is
      v_vSql                               varchar2(32767);
      rc1                                  sys_refcursor;
      rc2                                  sys_refcursor;
      rd                                   typ_obj_rpt_cde_pat;
      v_nIndex                             number;
      v_vPatientID                         varchar2(50);
      v_vCdeID                             varchar2(30);
      v_nIntakeID                          number(5);
      v_vValue                             varchar2(128);
   begin
      rd := typ_obj_rpt_cde_pat();

      v_vSql := 'select distinct t.patient_id, t.intake_id from data_intake t where t.complete = 1 '
                ||case 
                  when (c_nShowLatestIntake = 1) then 
                     'where t.intake_id = (select max(s.intake_id) from data_intake s where s.patient_id = t.patient_id) '
                  end;
      open rc1 for v_vSql;
      loop
         fetch rc1 into v_vPatientID, v_nIntakeID;
         exit when rc1%notfound;
         v_nIndex := 0;
         
         begin
            v_vSql := 'select cde_id from cde_stat_map order by cde_id';
            open rc2 for v_vSql;
            loop
               fetch rc2 into v_vCdeID;
               exit when rc2%notfound;
               v_nIndex := v_nIndex + 1;
               
               getPatientCdeValue (v_vPatientID, v_vCdeID, v_nIntakeID, pi_vKey, v_vValue);
               rd.setValue(v_nIndex, v_vValue);
            end loop;
            close rc2;
            
            pipe row (rd);
         exception
            when others
            then
               null;
         end;
      end loop;
      close rc1;
            
      -- part 2 (optional): add patient with no intake data
      v_vSql := 'select t.patient_id from patient_demographics t '
                ||'where 1 = '||c_nIncludeNoIntake||' '
                ||'and not exists (select * from data_intake s where s.patient_id = t.patient_id) ';
      open rc1 for v_vSql;
      loop
         fetch rc1 into v_vPatientID;
         exit when rc1%notfound;
         v_nIndex := 0;
         
         begin
            v_vSql := 'select cde_id from cde_stat_map order by cde_id';
            open rc2 for v_vSql;
            loop
               fetch rc2 into v_vCdeID;
               exit when rc2%notfound;
               v_nIndex := v_nIndex + 1;
               
               getPatientCdeValue (v_vPatientID, v_vCdeID, null, pi_vKey, v_vValue);
               rd.setValue(v_nIndex, v_vValue);
            end loop;
            close rc2;

            pipe row (rd);
            
         exception
            when others
            then
               null;
         end;
      end loop;
      close rc1; 

      return;
   end;

   /*table Patient Cde cache, use patient_cde_rpt table*/
   function tblPatientCde_Cached (
      pi_vKey                           in varchar2,
      pi_vProviderID                    in varchar2,
      pi_dDateRange_Start               in date,
      pi_dDateRange_End                 in date
      ) return                             typ_tbl_rpt_cde_pat pipelined
   is
      rd                                   typ_obj_rpt_cde_pat;
      v_vSql                               varchar2(32767);
      rc1                                  sys_refcursor;
      rc2                                  sys_refcursor;
      v_vPatientID                         varchar2(50);
      v_nIntakeID                          number(5);
      v_dDateUpdated                       date;
      v_nIndex                             number;
      v_vCdeID                             varchar2(30);
      v_vValue                             varchar2(128);
   begin
      rd := typ_obj_rpt_cde_pat();

      v_vSql := 'select t.* '
                ||'from patient_cde_rpt t '
                ||case 
                  when (c_nShowLatestIntake = 1) then 
                     'where t.intake_id = (select max(s.intake_id) from patient_cde_rpt s where s.patient_id = t.patient_id) '
                  end;
      open rc1 for v_vSql;
      loop
         fetch rc1 into v_vPatientID, v_nIntakeID, v_dDateUpdated, rd;
         exit when rc1%notfound;
         v_nIndex := 0;
         
         v_vSql := 'select cde_id from cde_stat_map order by cde_id';
         open rc2 for v_vSql;
         loop
            fetch rc2 into v_vCdeID;
            exit when rc2%notfound;
            v_nIndex := v_nIndex + 1;
         
            -- add encrypted demographic data
            if (instr(','||c_vEncrytedCdeIDs||',', ','||v_vCdeID||',') > 0)
            then
               getPatientCdeValue (v_vPatientID, v_vCdeID, v_nIntakeID, pi_vKey, v_vValue);
               rd.setValue(v_nIndex, v_vValue);
            end if;
         end loop;
         close rc2;
         
         pipe row (rd);
      end loop;
      close rc1;
      
      return;
   end;
   
   /*Get Patient Cde recordset*/
   procedure GetPatientCdeRS (
      pi_vSessionID                     in varchar2,
      pi_vSessionClientIP               in varchar2,
      pi_nUserID                        in number,
      --pi_nReportID                      in number,
      pi_vKey                           in varchar2,
      pi_vProviderID                    in varchar2,
      pi_vDateRange_Start               in varchar2,
      pi_vDateRange_End                 in varchar2,
      po_nStatusCode                   out number,
      po_vStatusComment                out varchar2,
      rs                               out sys_refcursor
      )
   is
      v_vSql                               varchar2(32767);
      rc                                   sys_refcursor;
      v_vVariableName                      varchar2(128);
      v_dDateRange_Start                   date := to_date(nvl(pi_vDateRange_Start, '19000101'), 'YYYYMMDD');
      v_dDateRange_End                     date := to_date(nvl(pi_vDateRange_End, '40001231'), 'YYYYMMDD');
      v_nIndex                             number := 0;
   begin
      open rc for 'select s.variable_name from cde_stat_map l, cde_stat s where l.cde_id = s.cde_id order by l.cde_id';
      loop
         fetch rc into v_vVariableName;
         exit when rc%notfound;
         
         v_nIndex := v_nIndex + 1;
         v_vSql := v_vSql
                   ||case when (v_vSql is not null) then ',' end
                   ||'c'||v_nIndex||' "'||substr(trim(v_vVariableName),1,30)||'"';
      end loop;
      close rc;
      
      v_vSql := 'select '||v_vSql||' from table (pck_rpt_cde.tblPatientCde (:P0,:P1,:P2,:P3)) t';
      open rs for v_vSql using pi_vKey, pi_vProviderID,v_dDateRange_Start,v_dDateRange_End;
  
   exception
      when others
      then
         po_nStatusCode    := Pck_Utl_Common.c_nResultStatus_Error;
         po_vStatusComment := 'PCK_RPT_CDE.GetPatientCdeRS(): '||sqlCode||'; '||sqlErrm;
   end;


   /*Get Patient Cde Cached recordset*/
   procedure GetPatientCdeRS_Cached (
      pi_vSessionID                     in varchar2,
      pi_vSessionClientIP               in varchar2,
      pi_nUserID                        in number,
      --pi_nReportID                      in number,
      pi_vKey                           in varchar2,
      pi_vProviderID                    in varchar2,
      pi_vDateRange_Start               in varchar2,
      pi_vDateRange_End                 in varchar2,
      po_nStatusCode                   out number,
      po_vStatusComment                out varchar2,
      rs                               out sys_refcursor
      )
   is
      v_vSql                               varchar2(32767);
      rc                                   sys_refcursor;
      v_vVariableName                      varchar2(128);
      v_dDateRange_Start                   date := to_date(nvl(pi_vDateRange_Start, '19000101'), 'YYYYMMDD');
      v_dDateRange_End                     date := to_date(nvl(pi_vDateRange_End, '40001231'), 'YYYYMMDD');
      v_nIndex                             number := 0;
   begin
      --setPatientCde ();
      
      open rc for 'select s.variable_name from cde_stat_map l, cde_stat s where l.cde_id = s.cde_id order by l.cde_id';
      loop
         fetch rc into v_vVariableName;
         exit when rc%notfound;
         
         v_nIndex := v_nIndex + 1;
         v_vSql := v_vSql
                   ||case when (v_vSql is not null) then ',' end
                   ||'c'||v_nIndex||' "'||substr(trim(v_vVariableName),1,30)||'"';
      end loop;
      close rc;
      
      v_vSql := 'select '||v_vSql||' from table (pck_rpt_cde.tblPatientCde_Cached (:P0,:P1,:P2,:P3)) t';
      open rs for v_vSql using pi_vKey, pi_vProviderID,v_dDateRange_Start,v_dDateRange_End;
  
   exception
      when others
      then
         po_nStatusCode    := Pck_Utl_Common.c_nResultStatus_Error;
         po_vStatusComment := 'PCK_RPT_CDE.GetPatientCdeRS_Cached(): '||sqlCode||'; '||sqlErrm;
   end;


end;
/

prompt
prompt Creating package body PCK_STAT
prompt ==============================
prompt
create or replace package body tbicds.PCK_STAT is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  /*
  Queries and returns static data 
  recordset by collections. 
  */
  procedure GetDataCollectionRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             pi_vDataCollection  in varchar2,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor)
  is
  
    v_vSQL varchar2(32767) := '';
  
  begin
  
    po_nStatusCode    := 0; --0 = success
    po_vStatusComment := '';
  
    open rs for
      select *
        from stat_data_collection t
       where t.collection_type = pi_vDataCollection
         and t.active = 1
       order by t.collection_item_id;
  
  exception
    when others then
      po_nStatusCode    := 1;
      po_vStatusComment := '';
  end;

end PCK_STAT;
/

prompt
prompt Creating package body PCK_SYSTEM_ID
prompt ===================================
prompt
create or replace package body tbicds.PCK_SYSTEM_ID is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
  /*This function will return a person id string*/
  function GetNewPersonID return varchar2 
  is
    v_vPatientID varchar2(72) := '';
    v_vPadding   varchar2(12) := '00000000';
  begin
    -- build the Patient ID
    v_vPatientID := v_vPatientID || c_vPatient;
    v_vPatientID := v_vPatientID || GenerateRandomString(6);
    v_vPatientID := v_vPatientID || GetDateTimeString;
    return v_vPatientID;
  end;

  /*This function will return a patient id string*/
  function GetNewPatientID(pi_vFirstName   in varchar2,
                           pi_vLastName    in varchar2,
                           pi_vDateOfBirth in varchar2,
                           pi_vGender      in varchar2,
                           pi_vSSN         in varchar2) return varchar2 
  is
  
    v_vPatientID varchar2(72) := '';
    v_vPadding   varchar2(12) := '00000000';
  
  begin
  
    -- build the Patient ID
    v_vPatientID := v_vPatientID || c_vPatient;
    v_vPatientID := v_vPatientID || GenerateRandomString(6);
    v_vPatientID := v_vPatientID || GetDateTimeString;
  
    return v_vPatientID;
  
  end;
  
  /*This function will return a provider id string*/
  function GetNewProviderID(pi_vFirstName   in varchar2,
                           pi_vLastName    in varchar2) return varchar2 is
  
    v_vProviderID varchar2(72) := '';
    v_vPadding   varchar2(12) := '00000000';
  
  begin
  
    -- build the Patient ID
    v_vProviderID := v_vProviderID || c_vProvider;
    v_vProviderID := v_vProviderID || GenerateRandomString(6);
    v_vProviderID := v_vProviderID || GetDateTimeString;
  
    return v_vProviderID;
  
  end;
  

  /*This function will return a provider id string*/
  function GetNewProviderID(pi_vFirstName in varchar2,
                            pi_vLastName  in varchar2,
                            pi_vNPI       in varchar2) return varchar2 
  is
  
    v_nPadLength number := 7;
    v_vPadding   varchar2(24) := '000000000000000000000000';
    v_vNPI       varchar2(24) := '';
    v_vNPISuffix varchar2(8) := '_NO_NPI';
  
    v_vProviderID varchar2(72) := '';
  
  begin
  
    --if  provider does not have NPI
    if ((pi_vNPI is null) OR (length(pi_vNPI) < 1)) then
      v_nPadLength := 14;
    else
      v_vNPI       := pi_vNPI;
      v_vNPISuffix := substr(v_vNPISuffix, -4);
    end if;
  
    v_vProviderID := v_vProviderID || c_vProvider || v_vNPISuffix;
    v_vProviderID := v_vProviderID || GenerateRandomString(6);
    v_vProviderID := v_vProviderID || GetDateTimeString;
    v_vProviderID := v_vProviderID ||
                     FromStringToNumber(substr(upper(pi_vFirstName ||
                                                     'AAAA'),
                                               1,
                                               4),
                                        2);
    v_vProviderID := v_vProviderID ||
                     FromStringToNumber(substr(upper(pi_vLastName || 'AAAA'),
                                               1,
                                               4),
                                        2);
    v_vProviderID := v_vProviderID || v_vNPI;
    v_vProviderID := v_vProviderID ||
                     substr(v_vPadding, (v_nPadLength * -1));
  
    return v_vProviderID;
  
  end;

  /* This function will return a contact patient id*/
  function GetNewContactPatientID(pi_vPatientID in varchar2) return varchar2 
  is
    v_vContactID varchar2(72) := '';
  begin
    v_vContactID := v_vContactID || c_vContact;
    v_vContactID := v_vContactID || substr(pi_vPatientID, 4);
    return v_vContactID;
  end;

  /*This function is used to return a numerical representation 
   of the alpha characters passed on.
   Where A=0 and Z=25
   The length of the returned value 
   for each character can be from 1 to 10 */
  function FromStringToNumber(pi_vString in varchar2, pi_nLength in number)
    return varchar2 
  is
  
    v_vResult  varchar2(32767) := '';
    v_vLetter  varchar2(1) := '';
    v_nCounter number;
    v_nASCII   number;
    v_nOffset  number := 65; --ASCII value for A is 65, we want the conversion starting at 0
    v_vPadding varchar2(10) := '0000000000';
  
  begin
  
    if length(pi_vString) > 0 then
      for v_nCounter in 1 .. length(pi_vString) loop
        v_vLetter := substr(upper(pi_vString), v_nCounter, 1);
        v_nASCII  := to_number(ic_utl_sec.VarcharToAscii(v_vLetter)) -
                     v_nOffset;
        v_vResult := v_vResult || substr(v_vPadding || to_char(v_nASCII),
                                         (pi_nLength * -1));
      
      end loop;
    end if;
    return v_vResult;
  end;

  /* This function is used to convert digits passed on to alpha characters
     Where 0 = A and 9 = J */
  function FromNumberToString(pi_vNumber in varchar2) return varchar2 
  
  is
  
    v_vResult  varchar2(32767) := '';
    v_vNumber  varchar2(1) := '';
    v_nNumber  number;
    v_nCounter number;
    v_nOffset  number := 65; --ASCII value for A is 65, we want the conversion starting at 0
  
  begin
  
    if length(pi_vNumber) > 0 then
      for v_nCounter in 1 .. length(pi_vNumber) loop
        v_vNumber := substr(upper(pi_vNumber), v_nCounter, 1);
        v_nNumber := to_number(v_vNumber) + v_nOffset;
        v_vResult := v_vResult || chr(v_nNumber);
      end loop;
    end if;
    return v_vResult;
  end;

  /* This function will generate a random alphanumeric characters string of N-Length*/
  function GenerateRandomString(pi_nLength in number) return varchar2 
  is
    v_vRandomChars raw(255);
    v_vResults     varchar2(255) := '';
  begin
    v_vRandomChars := dbms_crypto.randombytes(ceil(pi_nLength / 2));
    v_vResults     := v_vResults || v_vRandomChars;
    return v_vResults;
  end;

  /*
  This function will return a datetime string to the second resolution
  */
  function GetDateTimeString return varchar2 is
    v_vResults varchar2(24) := '';
  begin
    v_vResults := v_vResults || to_char(sysdate, 'mmddyyyyHHMMSS');
    return v_vResults;
  end;

end;
/

prompt
prompt Creating package body PCK_SYSTEM_SETTINGS
prompt =========================================
prompt
create or replace package body tbicds.PCK_SYSTEM_SETTINGS is
  /* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*Get site recordset*/
   procedure GetSiteRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             po_nStatusCode      out number,
                             po_vStatusComment   out varchar2,
                             rs                  out RetRefCursor) 
   is
   
   begin
      po_nStatusCode    := 0;
      po_vStatusComment := null;
      
      open rs for 'select t.* from tbicds.Site t';
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_SYSTEM_SETTINGS.GetSiteRS(): ' || sqlErrm;
   end;

end;
/

prompt
prompt Creating package body PCK_TEMPLATE
prompt ==================================
prompt
create or replace package body tbicds.PCK_TEMPLATE is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   
  /*get parsed template recordset*/ 
  procedure GetParsedTemplate2RS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_vPatientID       in varchar2,
                                 pi_vEncounterID     in varchar2,
                                 pi_nTemplateID      in number,
                                 pi_vKey             in varchar2,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor)
   is
      v_vSql          varchar2(4000);
      v_vTemplateText clob;
      rsTags          refCursor;
      rsFnTags        refCursor;
      v_recTags       tbicds.template_item%ROWTYPE;
      v_nPos          number;
      v_nPos2         number;
      v_vItemSQL      long;
      rsTagValue      refCursor;
      --v_vTagValue     varchar2(4000);
      v_vTagValue     clob;
      
      --Function tags
      v_vFnTag        varchar2(1000);
      v_nFnTagCount   number;
      v_nFnTagCtr     number;
      
      --Parameters. For the moment there is a limit of 3 parameters.
      type fnParams is varray(3) of varchar2(10);
      params fnParams := fnParams('', '', '');
   
      i number;
      p number; --parameter index

   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      v_vTemplateText   := '';
      v_nPos            := 0;
      v_nPos2           := 0;
      v_vItemSQL        := '';
      v_vTagValue       := '';
      v_vFnTag          := '';
  
      --get the tagged template text
      v_vSql := 'select template from tbicds.template where template_id = :P0';
      execute immediate v_vSql into v_vTemplateText using pi_nTemplateID;
      
      --open the recordset of all the possible tags
      open rsTags for 'select * from tbicds.template_item where description not like ''%(%)%''';
  
      --loop over items in the template_item table
      --and find and replace tags with values from the db
      LOOP
         v_recTags := null;
         FETCH rsTags INTO v_recTags;
         EXIT WHEN NOT rsTags%found;
         
         if v_recTags.description is not null then
            v_nPos := instr(v_vTemplateText, '[' || v_recTags.description || ']');
            
            if v_nPos != 0 then
               --format the sql to run for this tag
               v_vItemSQL := v_recTags.Item_Sql;
               v_vItemSQL := replace(v_vItemSQL, '~%s~', '''' || pi_vPatientID || '''');
               v_vItemSQL := replace(v_vItemSQL, '~%e~', '''' || pi_vEncounterID || '''');
               v_vItemSQL := replace(v_vItemSQL, '~%k~', '''' || pi_vKey || '''');
           
               --run the sql and get the value
               v_vTagValue := '';
               begin
                  open rsTagValue for v_vItemSQL;
                  FETCH rsTagValue INTO v_vTagValue;
                  close rsTagValue;
                
               exception
                  when others then
                     --error but keep processing the other tags
                     po_nStatusCode    := 1;
                     po_vStatusComment := po_vStatusComment || '<br>' || 'PCK_TEMPLATE.GetParsedTemplate2RS(): ' || sqlErrm;
                  
               end;
           
               v_vTemplateText := fnReplaceClob(v_vTemplateText, '[' || v_recTags.description || ']', v_vTagValue);
            end if;
         end if;
      END LOOP;
      CLOSE rsTags;
      
      
      --Function TAGs
      --open the recordset of all function tags
      open rsFnTags for 'select * from tbicds.template_item t where t.description like ''%(%)%''';
  
      --loop over the function tags and find and replace them with values from the db
      LOOP
         v_recTags := null;
         FETCH rsFnTags INTO v_recTags;
         EXIT WHEN NOT rsFnTags%found;
         
         if v_recTags.description is not null then
            v_nFnTagCount := REGEXP_COUNT(v_vTemplateText, replace(v_recTags.description,'()',''), 1, 'c');
--            v_vTemplateText := v_vTemplateText || to_char(v_nFnTagCount);
            for v_nFnTagCtr in 1 .. v_nFnTagCount
            loop
              --search for the function tag by using just the first part, e.g. "[fnName(" instead of "[fnName()]"
              --since they (the providers) could write anything between the parenthesis.
              v_nPos := instr(v_vTemplateText, '[' || replace(v_recTags.description,')',''));
              
              if v_nPos != 0 then
                 --there is one, so get the full fnTag they write, e.g. "[fnName(param1, param2)]"
                 v_nPos2 := instr(v_vTemplateText, ']', v_nPos);
                 v_vFnTag := substr(v_vTemplateText, v_nPos, v_nPos2 - v_nPos + 1); --full tag [fnName(param1, param2)]
                 
                 --Extract parameters from the fnTag (step 1 clear params variables, step 2 set parameter index & get the parameters
                 --clear params variables
                 for i in 1 .. params.count
                 loop
                   params(i) := '';
                 end loop;
                 --parameter index
                 p := 1;
                 --get the parameters
                 for i in instr(v_vFnTag, '(') + 1 .. length(v_vFnTag) - 2 -- Minus 2 to excluded the last two characters ")]" 
                 loop
                   if substr(v_vFnTag, i, 1) = ',' then
                     p := p + 1;
                   else
                     params(p) := params(p) || substr(v_vFnTag, i, 1);
                   end if;
                 end loop;
                 
                 --format the sql to run for this tag
                 v_vItemSQL := v_recTags.Item_Sql;
                 v_vItemSQL := replace(v_vItemSQL, '~%s~', '''' || pi_vPatientID || '''');
                 v_vItemSQL := replace(v_vItemSQL, '~%e~', '''' || pi_vEncounterID || '''');
                 v_vItemSQL := replace(v_vItemSQL, '~%k~', '''' || pi_vKey || '''');
                 
                 v_vItemSQL := replace(v_vItemSQL, '~%p1~', '''' || trim(params(1)) || '''');
                 v_vItemSQL := replace(v_vItemSQL, '~%p2~', '''' || trim(params(2)) || '''');
                 v_vItemSQL := replace(v_vItemSQL, '~%p3~', '''' || trim(params(3)) || '''');
             
                 --run the sql and get the value
                 v_vTagValue := '';
                 begin
                    open rsTagValue for v_vItemSQL;
                    FETCH rsTagValue INTO v_vTagValue;
                    close rsTagValue;
                  
                 exception
                    when others then
                       --error but keep processing the other tags
                       po_nStatusCode    := 1;
                       po_vStatusComment := po_vStatusComment || '<br>' || 'PCK_TEMPLATE.GetParsedTemplate2RS(): fnTag(x)' || sqlErrm;
                    
                 end;
             
                 v_vTemplateText := replace(v_vTemplateText, v_vFnTag, v_vTagValue);
              end if;
--                v_vTemplateText := v_vTemplateText || '.';
            end loop;
         end if;
--         v_vTemplateText := v_vTemplateText || ',';
      END LOOP;
      CLOSE rsFnTags;
--      v_vTemplateText := v_vTemplateText || ';';
      --open recordset
      open rs for select v_vTemplateText as template_text from dual;
  
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.GetParsedTemplate2RS(): ' || sqlErrm;
   end;

   /*
   Get template data tag recordset
   */
   procedure GetTemplateDataTagRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
  
      --open recordset
      v_vSql := 'select * from tbicds.template_item where active = 1 order by item_group_id';
      open rs for v_vSql;
  
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.GetTemplateDataTagRS(): ' || sqlErrm;
   end;

  /*
  Get template data tag group recordset
  */
  procedure GetTemplateDataTagGroupRS(pi_vSessionID       in varchar2,
                                      pi_vSessionClientIP in varchar2,
                                      pi_nUserID          in number,
                                      po_nStatusCode      out number,
                                      po_vStatusComment   out varchar2,
                                      rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
  
      --open recordset
      v_vSql := 'select * from tbicds.template_item_group where active = 1 order by group_id ';
      open rs for v_vSql;
  
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.GetTemplateDataTagGroupRS(): ' || sqlErrm;
   end;

  /*
  Get template type recordset
  */
  procedure GetTemplateTypeRS(pi_vSessionID       in varchar2,
                              pi_vSessionClientIP in varchar2,
                              pi_nUserID          in number,
                              po_nStatusCode      out number,
                              po_vStatusComment   out varchar2,
                              rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select * from tbicds.template_type where active = 1 order by type_id';
      open rs for v_vSql;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.GetTemplateTypeRS(): ' || sqlErrm;
   end;

  /*
  Get template recordset
  */
  procedure GetTemplateRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select t.*, tt.description as template_type '
                || 'from tbicds.template t, tbicds.template_type tt '
                || 'where t.type_id in (select type_id from tbicds.template_type where active = 1) '
                || 'and t.active = 1 '
                || 'and t.type_id = tt.type_id '
                || 'order by t.type_id ';
      open rs for v_vSql;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.GetTemplateRS(): ' || sqlErrm;
   end;

  /*
  Get the templates of TypeID = {1 = Subjective, 2 = Objective, 
  3 = Assessment/Plan, 4 = Outcomes}
  */
  procedure GetTemplateRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_nTypeID          in number,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select t.* '
                || 'from tbicds.template t '
                || 'where t.type_id = ' || pi_nTypeID || ' '
                || 'and t.active = 1 '
                || 'order by t.description';
      open rs for v_vSql;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.GetTemplateRS(): ' || sqlErrm;
   end;
   
   /*
   Update a template
   */
   procedure UpdateTemplate(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_nTemplateID      in number,
                           pi_nGroupID         in number,
                           pi_vTemplateName    in varchar2,
                           pi_vTemplateText    in clob,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'update tbicds.template set '
                || 'type_id = :P0, description = :P1, template = :P2 '
                || 'where template_id = :P3';
      execute immediate v_vSql using pi_nGroupID, pi_vTemplateName, pi_vTemplateText, pi_nTemplateID; 
      commit;

   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.UpdateTemplate(): ' || sqlErrm;
   end;

   /*
   Insert a template
   */
   procedure InsertTemplate(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           pi_nSOAPsectID      in number,
                           pi_vTemplateName    in varchar2,
                           pi_vTemplateText    in clob,
                           pi_nTempGroupID     in number,
                           po_nTemplateID      out number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      v_vSql := 'select tbicds.seqTemplateID.Nextval from dual';
      execute immediate v_vSql into po_nTemplateID;
       
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'insert into tbicds.template ('
                || 'template_id, type_id, description, template, creator_id, '
                || 'created_date, active, template_group_id) '
                || 'values (:P0, :P1, :P2, :P3, :P4, :P5, :P6, :P7)';
      execute immediate v_vSql using
         po_nTemplateID, pi_nSOAPsectID, pi_vTemplateName, pi_vTemplateText, pi_nUserID,
         sysdate, 1, pi_nTempGroupID;
      commit;

   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.UpdateTemplate(): ' || sqlErrm;
   end;

   /*
   Discontinue a template
   */
   procedure DiscontinueTemplate(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                pi_nTemplateID      in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'update tbicds.template set active = 0 where template_id = :P0';
      execute immediate v_vSql using pi_nTemplateID;
      commit;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.DiscontinueTemplate(): ' || sqlErrm;
   end;

   /*Insert Template Group*/
   procedure InsertTemplateGroup(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             --
                             pi_vTemplateGrpName in varchar2,
                             pi_vComments        in varchar2,
                             --
                             po_nTemplateGrpID out number,
                             po_nStatusCode    out number,
                             po_vStatusComment out varchar2)
   is
      v_vSql                               varchar2(4000);
      v_nTemplateGrpID number;
   begin
      v_vSql := 'select tbicds.seqtemplategrpid.Nextval from dual';
      execute immediate v_vSql into v_nTemplateGrpID;
      
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'insert into tbicds.template_group ('
                || 'template_group_id, group_name, comments, active, created_by, '
                || 'last_updated, last_updated_by) '
                || 'values (:P0, :P1, :P2, :P3, :P4, :P5, :P6) ';
      execute immediate v_vSql using
         v_nTemplateGrpID,pi_vTemplateGrpName, pi_vComments, 1, pi_nUserID,
         sysdate, pi_nUserID;
      commit;
      
      po_nTemplateGrpID := v_nTemplateGrpID;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.InsertTemplateGroup(): ' || sqlErrm;
         po_nTemplateGrpID := -1;
   end;

   /*Update Template Group*/
   procedure UpdateTemplateGroup(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             --
                             pi_nTemplateGrpID   in number,
                             pi_vTemplateGrpName in varchar2,
                             pi_vComments        in varchar2,
                             --
                             po_nStatusCode    out number,
                             po_vStatusComment out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'update tbicds.template_group t set '
                || 'group_name = :P0, '
                || 'comments = :P1, '
                || 'last_updated = sysdate, '
                || 'last_updated_by = :P2 '
                || 'where t.template_group_id = :P3 ';
      execute immediate v_vSql using pi_vTemplateGrpName, pi_vComments, pi_nUserID, pi_nTemplateGrpID;
      commit;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.UpdateTemplateGroup(): ' || sqlErrm;
   end;

   /*Discontinue Template Group*/
   procedure DiscontinueTemplateGroup(pi_vSessionID       in varchar2,
                                  pi_vSessionClientIP in varchar2,
                                  pi_nUserID          in number,
                                  --
                                  pi_nTemplateGrpID in number,
                                  --
                                  po_nStatusCode    out number,
                                  po_vStatusComment out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'update tbicds.template_group set '
                || 'active = 0, last_updated = sysdate, last_updated_by = :P0 '
                || 'where template_group_id = :P1';
      execute immediate v_vSql using pi_nUserID, pi_nTemplateGrpID;
      commit;
      
      --also discontinue templates associated to the group
      v_vSql := 'update tbicds.template set active = 0 where TEMPLATE_GROUP_ID = :P0';
      execute immediate v_vSql using pi_nTemplateGrpID;
      commit;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.DiscontinueTemplateGroup(): ' || sqlErrm;
   end;

   /*Get Template Groups recordset*/
   procedure GetTemplateGroupsRS(pi_vSessionID       in varchar2,
                                pi_vSessionClientIP in varchar2,
                                pi_nUserID          in number,
                                po_nStatusCode      out number,
                                po_vStatusComment   out varchar2,
                                rs                  out RetRefCursor) is
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      open rs for
         'select * from tbicds.template_group t where t.active = 1';
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.GetTemplateGroupsRS(): ' || sqlErrm;
   end;

   /*Get Group Templates*/
   procedure GetGroupTemplatesRS(pi_vSessionID       in varchar2,
                             pi_vSessionClientIP in varchar2,
                             pi_nUserID          in number,
                             
                             pi_nGroupID in number,
                             
                             po_nStatusCode    out number,
                             po_vStatusComment out varchar2,
                             rs                out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select t.*, tt.description as template_type '
                || 'from tbicds.template t, tbicds.template_type tt '
                || 'where t.type_id in (select type_id from tbicds.template_type where active = 1) '
                || 'and t.active = 1 '
                || 'and t.type_id = tt.type_id '
                || 'and t.template_group_id = :P0 '
                || 'order by t.type_id, t.template_group_id';
      open rs for v_vSql using pi_nGroupID;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_TEMPLATE.GetGroupTemplatesRS(): ' || sqlErrm;
   end;

   /*Get parsed template text*/
   function fnGetParsedTemplateText(pi_vPatientID    in varchar2,
                                   pi_vKey          in varchar2,
                                   pi_vTemplateText in varchar2) return clob 
   is
      v_vTemplateText clob;
      rsTags     refCursor;
      v_recTags  tbicds.template_item%ROWTYPE;
      v_nPos     number;
      v_vItemSQL long;
      rsTagValue  refCursor;
      v_vTagValue varchar2(4000);
   begin
      v_vTemplateText := '';
      v_nPos          := 0;
      v_vItemSQL      := '';
      v_vTagValue     := '';
      
      --get the tagged template text
      v_vTemplateText := pi_vTemplateText;
      
      --open the recordset of all the possible tags
      open rsTags for 'select * from tbicds.template_item';
      --loop over items in the template_item table
      --and find and replace tags with values from the db
      LOOP
         v_recTags := null;
         FETCH rsTags INTO v_recTags;
         EXIT WHEN NOT rsTags%found;
         
         if v_recTags.description is not null then
            v_nPos := instr(v_vTemplateText, '[' || v_recTags.description || ']');
            
            if v_nPos != 0 then
               --format the sql to run for this tag
               v_vItemSQL := v_recTags.Item_Sql;
               v_vItemSQL := replace(v_vItemSQL, '~%s~', '''' || pi_vPatientID || '''');
               v_vItemSQL := replace(v_vItemSQL, '~%k~', '''' || pi_vKey || '''');
               
               --run the sql and get the value
               v_vTagValue := '';
               begin
                  open rsTagValue for v_vItemSQL;
                  FETCH rsTagValue INTO v_vTagValue;
                  close rsTagValue;
               end;
               
               v_vTemplateText := replace(v_vTemplateText, '[' || v_recTags.description || ']', v_vTagValue);
            end if;
         end if;
      END LOOP;
      CLOSE rsTags;
      
      return v_vTemplateText;
   
   end;
   
   /*replace pieces in a  clob*/
   function fnReplaceClob (pi_source in clob
                          ,pi_search in varchar2
                          ,pi_replace in clob) return clob 
   is
   l_pos pls_integer;
   begin
        l_pos := instr(pi_source, pi_search);
        if l_pos > 0 then
           return substr(pi_source, 1, l_pos-1) || pi_replace || substr(pi_source, l_pos + length(pi_search));
           end if;
        return pi_source;
    end;
end;
/

prompt
prompt Creating package body PCK_USER
prompt ==============================
prompt
create or replace package body tbicds.PCK_USER is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   /*get login user record set*/
   procedure GetLoginUserRS (
      pi_vSessionID              in varchar2,
      pi_vSessionClientIP        in varchar2,
      pi_nUserID                 in number,
      pi_vKey                    in varchar2,
      pi_nFXUserID               in number,
      po_nStatusCode             out number,
      po_vStatusComment          out varchar2,
      rs                         out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
      v_nTemp         number;
      v_nCount        number;
      v_nPatUserType  number := 32768;
      v_nRovUserTypes  number := 59;
   begin
      v_nTemp := 0;
      po_nStatusCode := 0;--0 = success
      po_vStatusComment := '';
      v_nCount := 0;

      v_vSql := 'select count(*) '
                || 'from tbicds.fx_user t1, tbicds.fx_user_rights t2 '
                || 'where t2.fx_user_id = t1.fx_user_id '
                || 'and bitand(t2.user_type, :P0) > 0 '
                || 'and t1.fx_user_id = :P1 ';
      execute immediate v_vSql into v_nCount using v_nRovUserTypes, pi_nFXUserID;
      
      --open recordset
      if v_nCount > 0 then
         --check for user account
         v_vSql := 'select t1.fx_user_id, t1.date_last_login, t1.last_login_ip, t1.last_flogin_date, t1.last_flogin_ip, '
                   || 't1.flogin_attempts, t3.User_Type, t3.user_rights, t3.read_only, t2.dims_id, '
                   || 't2.provider_id, '
                   --less than or equal to zero means we are expired!
                   || 'floor(60 - (trunc(sysdate) - t1.date_password_changed)) as days_till_expiration, '
                   || 't2.name '
                   || 'from tbicds.fx_user t1, tbicds.app_user t2, tbicds.fx_user_rights t3 '
                   || 'where t2.fx_user_id = t1.fx_user_id '
                   || 'and t3.fx_user_id = t1.fx_user_id '
                   || 'and t1.fx_user_id = :P0 ';
         open rs for v_vSql using pi_nFXUserID;
      else
         --is a patient account
         v_vSql := 'select t1.fx_user_id, t1.date_last_login, t1.last_login_ip, t1.last_flogin_date, t1.last_flogin_ip, '
                    || 't1.flogin_attempts, :P0 as User_Type, 0 as user_rights, 0 as read_only, 0 as dims_id, '
                    || ''''' as provider_id, '
                    --less than or equal to zero means we are expired!
                    || 'floor(60 - (trunc(sysdate) - t1.date_password_changed)) as days_till_expiration, '
                    || '(tbicds.fnc_utl_decstr(t2.FIRST_NAME, :P1, t2.PATIENT_ID)||'' ''||tbicds.fnc_utl_decstr(t2.LAST_NAME, :P2, t2.PATIENT_ID)) as name '
                    || 'from tbicds.fx_user t1, tbicds.patient_demographics t2 '
                    || 'where t2.fx_user_id = t1.fx_user_id '
                    || 'and t1.fx_user_id = :P3 ';
         open rs for v_vSql using v_nPatUserType, pi_vKey, pi_vKey, pi_nFXUserID;
       end if;

   exception
      when others
      then
         po_nStatusCode := 1;
         po_vStatusComment := '421 - An error occurred while retrieving user infromation, Please contact your system administrator.';
   end;

end;
/

prompt
prompt Creating package body PCK_USER_ADMIN
prompt ====================================
prompt
create or replace package body tbicds.PCK_USER_ADMIN is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
   /*
   get a record set of users back that match criteria
   */
   procedure GetUserLookupRS(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vDMISID          in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2,
                            rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';  
   
      --open recordset
      v_vSql := 'SELECT distinct * '
                || 'FROM tbicds.app_user s '
                || 'WHERE DIMS_ID = :P0 '
                || 'ORDER BY upper(NAME) asc, ENTRY_DATE desc ';
      open rs for v_vSql using pi_vDMISID;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_USER_ADMIN.getUserLookupRS(): ' || sqlErrm;
   end;

   /*
   get a record set of users back that match criteria
   */
   procedure GetUserLookupBySearchRS(pi_vSessionID       in varchar2,
                                 pi_vSessionClientIP in varchar2,
                                 pi_nUserID          in number,
                                 pi_vSearchValue     in varchar2,
                                 po_nStatusCode      out number,
                                 po_vStatusComment   out varchar2,
                                 rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
      strSQL       varchar2(300);
      strSelectSQL varchar2(300);
      v_bHQRights     boolean;
      v_bMAJCOMRights boolean;
      v_vDMISID       varchar(50);
      v_nMAJCOMID     number;
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'select dims_id from tbicds.app_user where fx_user_id = :P0';
      execute immediate v_vSql into v_vDMISID using pi_nUserID;
      
      v_vSql := 'select majcom_id from tbicds.stat_dims_base where dims_id = :P0';
      execute immediate v_vSql into v_nMAJCOMID using v_vDMISID;
      
      --open recordset
      v_vSql := 'select * from tbicds.app_user s '
                || 'where UPPER(s.name) like :P0 '
                || 'order by s.dims_id, upper(s.name) asc, s.entry_date desc';
      open rs for v_vSql using UPPER('%'||pi_vSearchValue||'%');
      return;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_USER_ADMIN.getUserLookupBySearchRS(): ' || sqlErrm;
   end;

   /*
   Get user recordset
   */
   procedure GetSuatUserRS(pi_vSessionID       in varchar2,
                          pi_vSessionClientIP in varchar2,
                          pi_nUserID          in number,
                          pi_vProviderID      in varchar2,
                          po_nStatusCode      out number,
                          po_vStatusComment   out varchar2,
                          rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
      v_vDMISID varchar(50);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'select dims_id from tbicds.app_user where provider_id = :P0';
      execute immediate v_vSql into v_vDMISID using pi_vProviderID;
      
      --open recordset
      v_vSql := 'select user_type, name, rank, military_service_id, title, '
                || 'unit, corps, squadron, phone, email, '
                || 'dims_id, r.user_rights, locked '
                || 'from tbicds.app_user t, tbicds.fx_user_rights r '
                || 'where provider_id = :P0 '
                || 'and r.fx_user_id = t.fx_user_id '
                || 'and dims_id = :P1 ';
      open rs for v_vSql using pi_vProviderID, v_vDMISID;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_USER_ADMIN.GetSuatUserRS(): ' || sqlErrm;
   end;

   /*
   Get user name recordset
   */
   procedure GetSuatUserNameRS(pi_vSessionID       in varchar2,
                        pi_vSessionClientIP in varchar2,
                        pi_nUserID          in number,
                        pi_nFXUserID        in number,
                        po_nStatusCode      out number,
                        po_vStatusComment   out varchar2,
                        rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
      v_vDMISID varchar(50);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      v_vSql := 'select user_type, name, rank, military_service_id, title, '
                || 'unit, corps, squadron, phone, email, '
                || 'dims_id, r.user_rights, locked, t.graph_pref '
                || 'from tbicds.app_user t, tbicds.fx_user_rights r '
                || 'where t.fx_user_id = :P0 '
                || 'and r.fx_user_id = t.fx_user_id ';
      open rs for v_vSql using pi_nFXUserID;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_USER_ADMIN.GetSuatUserNameRS(): ' || sqlErrm;
   end;

   /*
   Get facility information recordset
   */
   procedure GetFacilityInfoRS(pi_vSessionID       in varchar2,
                           pi_vSessionClientIP in varchar2,
                           pi_nUserID          in number,
                           po_nStatusCode      out number,
                           po_vStatusComment   out varchar2,
                           rs                  out RetRefCursor) is
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      --open recordset
      open rs for
         'select * from tbicds.site t';
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_USER_ADMIN.GetFacilityInfoRS(): ' || sqlErrm;
   end;

   /*
   Insert a facility
   */
   procedure InsertFacilityInfo(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vSiteID          in varchar2,
                            pi_vSiteName        in varchar2,
                            pi_vSiteAddress1    in varchar2,
                            pi_vSiteCity        in varchar2,
                            pi_vSiteState       in varchar2,
                            pi_vSitePostalCode  in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'insert into tbicds.site ('
                || 'site_id, site_name, site_address_1, site_city, site_state, site_postal_code) '
                || 'values (:P0, :P1, :P2, :P3, :P4, :P5) ';
      execute immediate v_vSql using
         pi_vSiteID, pi_vSiteName, pi_vSiteAddress1, pi_vSiteCity, pi_vSiteState, pi_vSitePostalCode;
      commit;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_User_Admin.InserFacilityInfo(): ' || sqlErrm;
   end;

   /*
   Update a facility
   */
   procedure UpdateFacilityInfo(pi_vSessionID       in varchar2,
                            pi_vSessionClientIP in varchar2,
                            pi_nUserID          in number,
                            pi_vSiteID          in varchar2,
                            pi_vSiteName        in varchar2,
                            pi_vSiteAddress1    in varchar2,
                            pi_vSiteCity        in varchar2,
                            pi_vSiteState       in varchar2,
                            pi_vSitePostalCode  in varchar2,
                            po_nStatusCode      out number,
                            po_vStatusComment   out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'update tbicds.site set '
                || 'site_id = :P0, '
                || 'site_name = :P1, '
                || 'site_address_1 = :P2, '
                || 'site_city = :P3, '
                || 'site_state = :P4, '
                || 'site_postal_code = :P5 ';
      execute immediate v_vSql using
         pi_vSiteID, pi_vSiteName, pi_vSiteAddress1, pi_vSiteCity, pi_vSiteState, pi_vSitePostalCode; 
      commit;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_USER_ADMIN.UpdateFacilityInfo(): ' || sqlErrm;
   end;

   /*
   Update graph preference
   */
   procedure UpdateGraphPref(pi_vSessionID       in varchar2,
                         pi_vSessionClientIP in varchar2,
                         pi_nUserID          in number,
                         pi_nGraphOpt        in varchar2,
                         po_nStatusCode      out number,
                         po_vStatusComment   out varchar2)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'update tbicds.app_user t set t.graph_pref = :P0 where t.fx_user_id = :P1 ';
      execute immediate v_vSql using pi_nGraphOpt, pi_nUserID; 
      commit;
   
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_USER_ADMIN.UpdateGraphPref(): ' || sqlErrm;
   end;

   /*
   Get graph preference
   */
   procedure GetGraphPref(pi_vSessionID       in varchar2,
                      pi_vSessionClientIP in varchar2,
                      pi_nUserID          in number,
                      po_nStatusCode      out number,
                      po_vStatusComment   out varchar2,
                      rs                  out RetRefCursor)
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'select * from tbicds.app_user t where t.fx_user_id = :P0';
      open rs for v_vSql using pi_nUserID;
      
   exception
      when others then
         po_nStatusCode    := 1;
         po_vStatusComment := 'PCK_USER_ADMIN.GetGraphPref(): ' || sqlErrm;
   end;

end;
/

prompt
prompt Creating package body PCK_USER_CALENDAR
prompt =======================================
prompt
CREATE OR REPLACE PACKAGE body TBICDS.PCK_USER_CALENDAR
IS
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* Get all events recordset */
PROCEDURE GetAllEventsRS(
    pi_vSessionID       IN VARCHAR2,
    pi_vSessionClientIP IN VARCHAR2,
    pi_nUserID          IN NUMBER,
    rs OUT PCK_COMMON.refCursor,
    po_nStatusCode OUT NUMBER,
    po_vStatusComment OUT VARCHAR2)
is
  v_vSQL VARCHAR2(32767);
BEGIN
  -- reset status parameters
  po_nStatusCode    := 0;
  po_vStatusComment := '';
  --define sql statement string
  --open cursor
  OPEN rs FOR SELECT * FROM dev_calendar t;
EXCEPTION
WHEN OTHERS THEN
  po_nStatusCode    := 1;
  po_vStatusComment := '';
END;

/* Update event by event_id */
PROCEDURE UpdateEvent(
    pi_vSessionID       IN VARCHAR2,
    pi_vSessionClientIP IN VARCHAR2,
    pi_nUserID          IN NUMBER,
    pi_nEventID         IN NUMBER,
    pi_nCalendarID      IN NUMBER,
    pi_vTitle           IN VARCHAR2,
    pi_vStartDate       IN VARCHAR2,
    pi_vEndDate         IN VARCHAR2,
    pi_vLocation        IN VARCHAR2,
    pi_vNotes           IN VARCHAR2,
    pi_vReminder        IN VARCHAR2,
    pi_vUrl             IN VARCHAR2,
    pi_nAllDay          IN NUMBER,
    po_nStatusCode OUT NUMBER,
    po_vStatusComment OUT VARCHAR2)
is
  dtStartDate DATE := NULL;
  dtEndDate   DATE := NULL;
BEGIN
  -- reset status parameters
  po_nStatusCode          := 0;
  po_vStatusComment       := '';
  IF LENGTH(pi_vStartDate) > 0 THEN
    dtStartDate           := to_date(pi_vStartDate, 'MM/DD/YYYY HH:MI:SS AM');
  END IF;
  IF LENGTH(pi_vEndDate) > 0 THEN
    dtEndDate           := to_date(pi_vEndDate, 'MM/DD/YYYY HH:MI:SS AM');
  END IF;
  UPDATE dev_calendar t
  SET t.title      = pi_vTitle,
    t.start_date   = dtStartDate,
    t.end_date     = dtEndDate,
    t.calendar_id  = pi_nCalendarID,
    t.is_all_day   = pi_nAllDay,
    t.location     = pi_vLocation,
    t.notes        = pi_vNotes,
    t.reminder     = pi_vReminder,
    t.url          = pi_vUrl
  WHERE t.event_id = pi_nEventID;
  COMMIT;
EXCEPTION
WHEN OTHERS THEN
  po_nStatusCode    := 1;
  po_vStatusComment := '';
END;

/* Insert event */
PROCEDURE InsertEvent(
    pi_vSessionID       IN VARCHAR2,
    pi_vSessionClientIP IN VARCHAR2,
    pi_nUserID          IN NUMBER,
    --pi_nEventID         IN NUMBER,
    pi_nCalendarID      IN NUMBER,
    pi_vTitle           IN VARCHAR2,
    pi_vStartDate       IN VARCHAR2,
    pi_vEndDate         IN VARCHAR2,
    pi_vLocation        IN VARCHAR2,
    pi_vNotes           IN VARCHAR2,
    pi_vReminder        IN VARCHAR2,
    pi_vUrl             IN VARCHAR2,
    pi_nAllDay          IN NUMBER,
    po_nStatusCode OUT NUMBER,
    po_vStatusComment OUT VARCHAR2)
is
  dtStartDate DATE := NULL;
  dtEndDate   DATE := NULL;
BEGIN
  -- reset status parameters
  po_nStatusCode          := 0;
  po_vStatusComment       := '';
  IF LENGTH(pi_vStartDate) > 0 THEN
    dtStartDate           := to_date(pi_vStartDate, 'MM/DD/YYYY HH:MI:SS AM');
  END IF;
  IF LENGTH(pi_vEndDate) > 0 THEN
    dtEndDate           := to_date(pi_vEndDate, 'MM/DD/YYYY HH:MI:SS AM');
  END IF;
  INSERT
  INTO DEV_CALENDAR
    (
      CALENDAR_ID,
      END_DATE,
      IS_ALL_DAY,
      LOCATION,
      NOTES,
      REMINDER,
      START_DATE,
      TITLE,
      URL,
      PATIENT_ID,
      PROVIDER_ID
    )
    VALUES
    (
      pi_nCalendarID,
      dtEndDate,
      pi_nAllDay,
      pi_vLocation,
      pi_vNotes,
      pi_vReminder,
      dtStartDate,
      pi_vTitle,
      pi_vUrl,
      '',
      ''
    );
  COMMIT;
EXCEPTION
WHEN OTHERS THEN
  po_nStatusCode    := 1;
  po_vStatusComment := '';
END;

/* Get all calendars recordset */
PROCEDURE GetAllCalendarsRS
  (
    pi_vSessionID       IN VARCHAR2,
    pi_vSessionClientIP IN VARCHAR2,
    pi_nUserID          IN NUMBER,
    rs OUT PCK_COMMON.refCursor,
    po_nStatusCode OUT NUMBER,
    po_vStatusComment OUT VARCHAR2
  )
is
  v_vSQL VARCHAR2(32767);
BEGIN
  -- reset status parameters
  po_nStatusCode    := 0;
  po_vStatusComment := '';
  --define sql statement string
  --open cursor
  OPEN rs FOR SELECT * FROM dev_stat_calendar t WHERE t.active = 1;
EXCEPTION
WHEN OTHERS THEN
  po_nStatusCode    := 1;
  po_vStatusComment := '';
END;

END PCK_USER_CALENDAR;
/

prompt
prompt Creating package body PCK_UTL_COMMON
prompt ====================================
prompt
create or replace package body tbicds.PCK_UTL_COMMON is
 /* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
end;
/

prompt
prompt Creating package body PCK_UTL_EXPORT_DATA
prompt =========================================
prompt
create or replace package body tbicds.PCK_UTL_EXPORT_DATA is
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/   
   /*get static data item*/
   function demoValue_STAT (
      pi_vVariableName                  in varchar2,
      pi_vVariableValue                 in varchar2
      ) return                             varchar2
   is
      v_vValue                             varchar2(4000);
      v_vSql                               varchar2(4000);
   begin
      v_vSql := 'select item from stat_data_collection '
                ||'where collection_type = ''_'||pi_vVariableName||''' and collection_item_id = :P';
      execute immediate v_vSql into v_vValue using pi_vVariableValue;
      return v_vValue;
      
   exception
      when others 
      then 
         return null;
   end;

   /*Get patient data with static data*/
   function demoValue_TBL (
      pi_vVariableName                  in varchar2,
      pi_vPatientID                     in varchar2
      ) return                             varchar2
   is
      v_vValue                             varchar2(4000);
      v_vSql                               varchar2(4000); 
   begin
      v_vSql := 'select wm_concat(s.item) '
                ||'from patient_'||pi_vVariableName||' t, stat_data_collection s '
                ||'where t.patient_id = :P '
                ||'and s.collection_type = ''_'||pi_vVariableName||''' '
                ||'and t.'||pi_vVariableName||'_ID = s.collection_item_id'; 
      execute immediate v_vSql into v_vValue using pi_vPatientID;
      return v_vValue;
      
   exception
      when others 
      then 
         return null;
   end;

   /*Get socioeconomic data*/
   function demoValue_SE (
      pi_vVariableName                  in varchar2,
      pi_vPatientID                     in varchar2
      ) return                             varchar2
   is
      v_vValue                             varchar2(4000);
      v_vSql                               varchar2(4000); 
   begin
      v_vSql := 'select wm_concat(s.item) '
                ||'from patient_socioeconomic t, stat_data_collection s '
                ||'where t.patient_id = :P '
                ||'and s.collection_type = ''_'||pi_vVariableName||''' '
                ||'and t.'||pi_vVariableName||'_ID = s.collection_item_id';
      execute immediate v_vSql into v_vValue using pi_vPatientID;
      return v_vValue;
      
   exception
      when others 
      then 
         return null;
   end;
   
   /*Get last response value*/
   function latestResponseValue (
      pi_vPatientID                     in varchar2,
      pi_nMID                           in number,
      pi_nTID                           in number,
      pi_nQID                           in number
      ) return                             varchar2
   is
      v_vSql                               varchar2(4000);
      v_vValue                             varchar2(32767);
   begin
      v_vSql := 'select response_value '
                ||'from data_intake_responses t '
                ||'where patient_id = :P and mid = :M and tid = :T and qid = :Q '
                ||'and intake_id = ('
                ||'select max(intake_id) from data_intake_responses s '
                ||'where s.patient_id = t.patient_id and s.mid = t.mid and s.tid = t.tid and s.qid = t.qid) ';
      execute immediate v_vSql into v_vValue using pi_vPatientID, pi_nMID, pi_nTID, pi_nQID;

      return v_vValue;
      
   exception
      when others 
      then 
         return null;
   end;
      
   /*Get last radio responcse value*/
   function latestResponseValue_Radio (
      pi_vPatientID                     in varchar2,
      pi_nMID                           in number,
      pi_nTID                           in number,
      pi_nQID                           in number
      ) return                             varchar2
   is
      v_vSql                               varchar2(4000);
      v_vSql_SkipShow                      varchar2(4000);
      v_vValue                             varchar2(32767);
      v_nRID                               number;
      v_nTID                               number;
      v_nQID                               number;
      v_vSkipShow                          varchar2(128);
   begin
      v_vSql := 'select response_value, rid '
                ||'from data_intake_responses t '
                ||'where patient_id = :P and mid = :M and tid = :T and qid = :Q '
                ||'and intake_id = ('
                ||'select max(intake_id) from data_intake_responses s '
                ||'where s.patient_id = t.patient_id and s.mid = t.mid and s.tid = t.tid and s.qid = t.qid) ';
      execute immediate v_vSql into v_vValue, v_nRID using pi_vPatientID, pi_nMID, pi_nTID, pi_nQID;

      if (regexp_like (v_vValue, 'other', 'i'))
      then
         v_vSql_SkipShow := 'select skip_show from intake_response where mid = :M and tid = :T and qid = :Q and rid = :R';
         execute immediate v_vSql_SkipShow into v_vSkipShow using pi_nMID, pi_nTID, pi_nQID, v_nRID;
         
         v_nTID := to_number(substr(regexp_substr(v_vSkipShow, 'TID[[:digit:]]+'), 4));
         v_nQID := to_number(substr(regexp_substr(v_vSkipShow, 'QID[[:digit:]]+'), 4));
         
         execute immediate v_vSql into v_vValue, v_nRID using pi_vPatientID, pi_nMID, v_nTID, v_nQID;
      end if;

      return v_vValue;
      
   exception
      when others 
      then 
         return null;
   end;

   /*Get demographic variables*/
   function getDemoVariables (
      pi_vDataIncluded                  in varchar2,
      pi_vKey                           in varchar2
      ) return                             varchar2
   is
   
      v_vVariableList                      varchar2(32767);
      v_vVariable                          varchar2(128);
      v_vValue                             varchar2(4000);

      -- addVariable()
      procedure addVariable (
         pi_vDataIncluded                  in varchar2,
         pi_vVariable                      in varchar2,
         pi_vValue                         in varchar2,
         pio_vVariableList             in out varchar2
         )
      is
      begin
         if (instr(pi_vDataIncluded,','||pi_vVariable||',') > 0 or pi_vVariable = 'PATIENT_ID')
         then
            pio_vVariableList := pio_vVariableList||','||pi_vValue||' '||pi_vVariable;
         elsif (c_nShowNotIncluded = 1)
         then
            pio_vVariableList := pio_vVariableList||','||'null '||pi_vVariable;
         end if;
      end;
   begin
      v_vVariable := 'PATIENT_ID';
      v_vValue := 'D.PATIENT_ID';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);
      
      /*v_vVariable := 'DATE_COMPLETED';
      v_vValue := 'I.DATE_COMPLETED';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);*/

      v_vVariable := 'CITY';
      v_vValue := v_vVariable;
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'STATE';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_STAT('''||'STATES'||''',d.'||v_vVariable||'_ID)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);
      
      v_vVariable := 'POSTAL_CODE';
      v_vValue := v_vVariable;
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);
      
      v_vVariable := 'DOB';
      v_vValue := 'ic_utl_sec.decryptdata('||v_vVariable||','''||pi_vKey||''',d.patient_id)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);
      
      v_vVariable := 'GENDER';
      v_vValue := 'ic_utl_sec.decryptdata('||v_vVariable||','''||pi_vKey||''',d.patient_id)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);
      
      v_vVariable := 'DUTY_STATUS';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_STAT('''||v_vVariable||''',d.'||v_vVariable||'_ID)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'PREFERRED_LANGUAGE';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_STAT('''||v_vVariable||''',d.'||v_vVariable||'_ID)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'ETHNICITY';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_TBL('''||v_vVariable||''',d.patient_id)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'RACE';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_TBL('''||v_vVariable||''',d.patient_id)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'HAND_PREFERENCE';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_STAT('''||v_vVariable||''',d.'||v_vVariable||'_ID)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'HIGHEST_GRADE_LEVEL';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_SE('''||'HIGHEST_GRADE'||''',d.patient_id)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'HIGHEST_DEGREE_OBTAINED';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_SE('''||'HIGHEST_DEGREE'||''',d.patient_id)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'MARITAL_STATUS';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_SE('''||v_vVariable||''',d.patient_id)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);
      
      v_vVariable := 'EMPLOYMENT_STATUS';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_SE('''||v_vVariable||''',d.patient_id)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'JOB_CLASS_CAT';
      v_vValue := 'PCK_UTL_EXPORT_DATA.demoValue_SE('''||'JOB_CLASSIFICATION'||''',d.patient_id)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);
      
      v_vVariable := 'PRIMARY_IMP';
      v_vValue := 'PCK_UTL_EXPORT_DATA.latestResponseValue_Radio(d.patient_id, 3000, 1, 1)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'PRIMARY_IMP_DATE';
      v_vValue := 'PCK_UTL_EXPORT_DATA.latestResponseValue(d.patient_id, 3000, 1, 3)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'MCH_INJURY';
      v_vValue := 'PCK_UTL_EXPORT_DATA.latestResponseValue_Radio(d.patient_id, 3000, 1, 4)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      v_vVariable := 'COMORBIDITY';
      v_vValue := 'PCK_UTL_EXPORT_DATA.latestResponseValue(d.patient_id, 3000, 1, 6)';
      addVariable(pi_vDataIncluded, v_vVariable, v_vValue, v_vVariableList);

      return v_vVariableList||' ';

   exception
      when others
      then
         return null;
   end;
   
   /*get where clause*/
   function getWhereclause (
      pi_vFilters                       in varchar2
      ) return                             varchar2
   is
      v_vWhereClause                       varchar2(4000);
      v_vDateFormat_Filter                 varchar2(30) := 'yyyymmdd';
      v_vTemp                              varchar2(4000);
      v_vFilter                            varchar2(4000);
      v_vValue                             varchar2(128);
      v_nPos                               number;
      v_bOutpatient                        boolean := false;                
      v_bInpatient                         boolean := false;                
      v_vClinicalStt                       varchar2(3);
      v_nProgram                           number := -1;
      v_nRegion                            number := -1;
      v_nSite                              number := -1;
   begin
      -- set where clause using filters
      v_vTemp := lower(pi_vFilters)||',';
      while (v_vTemp is not null)
      loop
         v_nPos := instr(v_vTemp, ',');
         v_vFilter := substr(v_vTemp, 1, v_nPos-1);
         v_vTemp := substr(v_vTemp, v_nPos+1);
         
         if (v_vFilter like 'start_date%')
         then
            v_vValue := regexp_substr(v_vFilter, '[[:digit:]]+');
            v_vFilter := 'trunc(i.date_completed) >= to_date('''||v_vValue||''','''||v_vDateFormat_Filter||''')';
         
         elsif (v_vFilter like 'end_date%')
         then
            v_vValue := regexp_substr(v_vFilter, '[[:digit:]]+');
            v_vFilter := 'trunc(i.date_completed) <= to_date('''||v_vValue||''','''||v_vDateFormat_Filter||''')';

         elsif (v_vFilter like 'region%')
         then
            v_vValue := regexp_substr(v_vFilter, '[[:digit:]]+');
            v_nRegion := v_vValue;
            v_vFilter := 'i.region_id = '||v_vValue;
         
         elsif (v_vFilter like 'site%')
         then
            v_vValue := regexp_substr(v_vFilter, '[[:digit:]]+');
            v_nSite := v_vValue;
            v_vFilter := 'i.site_id = '||v_vValue;
         
         elsif (v_vFilter like 'outpatient%')
         then
            v_vValue := regexp_substr(v_vFilter, '[[:digit:]]+');
            v_bOutpatient := (v_vValue = '1');
            v_vFilter := null;
            
         elsif (v_vFilter like 'inpatient%')
         then
            v_vValue := regexp_substr(v_vFilter, '[[:digit:]]+');
            v_bInpatient := (v_vValue = '1');
            v_vFilter := null;

         elsif (v_vFilter like 'program%')
         then
            v_vValue := regexp_substr(v_vFilter, '[[:digit:]]+');
            v_nProgram := v_vValue;
            v_vFilter := null;
         else
            v_vFilter := null;
         end if;
         
         if (v_vFilter is not null)
         then
            v_vWhereClause := v_vWhereClause||'and '||v_vFilter||' ';
         end if;
      end loop;                
      
      if (v_bOutpatient and v_bInpatient) or
         (not v_bOutpatient and not v_bInpatient)
      then
        v_vClinicalStt := '1,2';
      elsif v_bOutpatient and not v_bInpatient
      then
        v_vClinicalStt := '1';
      elsif not v_bOutpatient and v_bInpatient
      then
        v_vClinicalStt := '2';
      end if;
      
      --Program filter
      v_vWhereClause := v_vWhereClause      
                        ||'and exists(select 1 from pat_treatment_program t '
                        ||'where t.patient_id = d.patient_id '
                        ||'  and t.treatment_id in(select treatment_id '
                                                ||'from pat_treatment t1 '
                                                ||'where t1.patient_id = d.patient_id '
                                                ||'  and t1.treatment_type_id in('||v_vClinicalStt||')'
                                                ||'  and t1.region_id='||v_nRegion
                                                ||'  and t1.site_id='||v_nSite||') '
                        ||'  and t.cpa_id = (select cpa_id '
                                          ||'from CPA t1 '
                                          ||'where t1.region_id='||v_nRegion
                                          ||'  and t1.site_id='||v_nSite
                                          ||'  and t1.cpa_type_id='||v_nProgram||'))';
 
      
      --if (v_bOutpatient and not v_bInpatient)
      --then
      --   v_vWhereClause := v_vWhereClause
      --                     ||'and exists (select * from pat_treatment s '
      --                     ||'where s.treatment_type_id = 1 and s.patient_id = i.patient_id) ';
    --  
      --elsif (not v_bOutpatient and v_bInpatient)
      --then
        -- v_vWhereClause := v_vWhereClause
          --                 ||'and exists (select * from pat_treatment s '
            --               ||'where s.treatment_type_id = 2 and s.patient_id = i.patient_id) ';
     -- end if;
      
      return v_vWhereClause;

   exception
      when others
      then
         return null;
   end;

   /*Get response value*/
   function responseValue (
      pi_vPatientID                     in varchar2,
      pi_nIntakeID                      in number,
      pi_nMID                           in number,
      pi_nTID                           in number,
      pi_nQID                           in number,
      pi_nRID                           in number
      ) return                             varchar2
   is
      v_exNoModule                         exception;
      v_nExists                            number;
      v_vSql                               varchar2(4000);
      v_nDisplayType                       number;
      v_vValue                             varchar2(4000);
   begin
   
      begin
        v_vSql := 'select 1 from data_intake_responses '
                  ||'where patient_id = :P and intake_id = :I and mid = :M and rownum = 1 ';  
        execute immediate v_vSql into v_nExists using pi_vPatientID, pi_nIntakeID, pi_nMID;
      exception
        when no_data_found
        then
           v_nExists := 0;
           raise v_exNoModule;
        when others
        then
           v_nExists := 0;
      end;
   
   
      v_vSql := 'select response_value from data_intake_responses '
                ||'where patient_id = :P and intake_id = :I and mid = :M and tid = :T and qid = :Q and rid = :R and rownum = 1 ';
      execute immediate v_vSql into v_vValue using pi_vPatientID, pi_nIntakeID, pi_nMID, pi_nTID, pi_nQID, pi_nRID;
   
      v_vSql := 'select display_type from intake_response where mid = :M and tid = :T and qid = :Q and rid = :R and rownum = 1';
      execute immediate v_vSql into v_nDisplayType using pi_nMID, pi_nTID, pi_nQID, pi_nRID;
      
      if (v_nDisplayType not in (3,4,22))
      then
         v_vValue := '1';
      end if;
      
      return v_vValue;
      
   exception
      when v_exNoModule
      then
         return ''; -- return blank if no module has been taken
      when no_data_found 
      then 
         return '0';
      when others
      then 
         return sqlerrm;
   end;
            
   /*generate CSV data*/
   procedure generateCsv (
      pi_nRequestID                     in number,
      pi_vKey                           in varchar2
      )
   is
      v_vSql                               varchar2(32767);
      rd                                   exp_statistical_rpt%rowtype;                                   
      v_vDataIncluded                      varchar2(4000);
      rc                                   sys_refcursor;
      v_nCurID                             number;
      v_nColumnCount                       number := 0;
      v_sDescTab                           dbms_sql.desc_tab;
      v_vColumnValue                       varchar2(4000);
      v_nColumnValue                       number;
      v_dColumnValue                       date;
      v_vDateFormat                        varchar2(30) := 'YYYY/MM/DD HH24:MI:SS';
      v_vDelimiter                         varchar2(5) := ',';
      v_lData                              clob;
      v_nColumnIndex_PatientID             number := 0;
      v_nColumnIndex_IntakeID              number := 0;
      v_vPatientID                         varchar2(60);
      v_nIntakeID                          number;
      v_nCurrentMID                        number;
      v_vBuffer                            varchar2(32767);
      v_nLastRownum                        number;
      v_nFilterByMID                       number := 0;
      
      v_vMsg                               varchar2(4000);
         
      procedure appendToClob (
         pio_lData                     in out clob,
         pio_vBuffer                   in out varchar2,
         pi_vText                          in varchar2
         )
      is
      begin
         if (length(pio_vBuffer)+length(pi_vText) >= 32767)
         then
            pio_lData := pio_lData||pio_vBuffer||pi_vText;
            pio_vBuffer := null;
         else
            pio_vBuffer := pio_vBuffer||pi_vText;
         end if;
      end;
   begin
      -- get parameters
      v_vSql := 'select * from exp_statistical_rpt where request_id = :P0';
      execute immediate v_vSql into rd using pi_nRequestID;
      v_vDataIncluded := ','||upper(rd.data_included)||',';

      v_vSql := 'select 1 from dual where exists(select mid from intake_module t where active=1 and instr('''||v_vDataIncluded||''',t.MID) > 0)';
      begin
        execute immediate v_vSql into v_nFilterByMID;
      exception
        when others then
          v_nFilterByMID :=0;
      end;
      
      -- construct sql
      if v_nFilterByMID = 1 then
        v_vSql := 'select i.PATIENT_ID as PAT_ID, i.INTAKE_ID '
                  ||getDemoVariables(v_vDataIncluded, pi_vKey)
                  ||'from patient_demographics d, pat_pw_event_module i, pat_pw_event e '
                  ||'where d.patient_id = i.patient_id '
                  ||'and e.pat_pw_event_id = i.pat_pw_event_id and e.status = 2 '
                  ||'and exists (select * from data_intake r where r.patient_id = i.patient_id and r.intake_id = i.intake_id and r.mid = i.mid) '
                  ||'and case when instr('''||v_vDataIncluded||''',i.MID) > 0 then 1 else 0 end = 1 '
                  ||getWhereclause (rd.filters);
                  
        if (c_nShowLatestIntakeOnly = 1) 
        then
           v_vSql := v_vSql||'and i.intake_id = (select max(s.intake_id) from pat_pw_event_module s where s.patient_id = i.patient_id '
                     ||replace(getWhereclause (rd.filters), ' i.', ' s.')||') ';
        end if;
      else
        v_vSql := 'select i.PATIENT_ID as PAT_ID, i.INTAKE_ID '
                  ||getDemoVariables(v_vDataIncluded, pi_vKey)
                  ||'from patient_demographics d, pat_pw_event_module i, pat_pw_event e '
                  ||'where d.patient_id = i.patient_id '
                  ||'and e.pat_pw_event_id = i.pat_pw_event_id and e.status = 2 '
                  ||'and exists (select * from data_intake r where r.patient_id = i.patient_id and r.intake_id = i.intake_id and r.mid = i.mid) '
                  ||'and i.intake_id = (select max(s.intake_id) from pat_pw_event_module s where s.patient_id = i.patient_id '
                  ||replace(getWhereclause (rd.filters), ' i.', ' s.')||') '
                  ||getWhereclause (rd.filters);
      end if;            
      
      v_vSql := v_vSql||'order by i.patient_id, i.intake_id ';
      
      -- switch from native dynamic SQL to dbms_sql package
      open rc for v_vSql;
      v_nCurID := dbms_sql.to_cursor_number (rc);
      dbms_sql.describe_columns (v_nCurID, v_nColumnCount, v_sDescTab);

      -- define columns and set header in csv
      for i in 1..v_nColumnCount
      loop
         -- set column index for patient_id and intake_id
         if (v_sDescTab(i).col_name = 'PAT_ID')
         then
            v_nColumnIndex_PatientID := i;
         elsif (v_sDescTab(i).col_name = 'INTAKE_ID')
         then
            v_nColumnIndex_IntakeID := i;
         end if;
         
         -- define columns 
         if (v_sDescTab(i).col_type = 2)
         then
            dbms_sql.define_column (v_nCurID, i, v_nColumnValue);
         elsif (v_sDescTab(i).col_type = 12)
         then
            dbms_sql.define_column (v_nCurID, i, v_dColumnValue);
         else
            dbms_sql.define_column (v_nCurID, i, v_vColumnValue, 4000);
         end if;
            
         -- set column name header
         if (v_sDescTab(i).col_name not in ('PAT_ID','INTAKE_ID'))
         then
            appendToClob (v_lData, v_vBuffer, '"'||v_sDescTab(i).col_name||'"'||v_vDelimiter);
         end if;
      end loop;

      -- get the last rownum to 
      v_vSql := 'select max(rn) from vw_utl_rpt_intake_response '
                || case when (c_nShowNotIncluded != 1) then 'where instr('''||v_vDataIncluded||''','',''||mid||'','') >= 1' end;
      execute immediate v_vSql into v_nLastRownum;
      
      -- add instrument data column names
      v_nCurrentMID := 0;
      for r in (select * from vw_utl_rpt_intake_response
                 where instr(v_vDataIncluded,','||mid||',') >= case when (c_nShowNotIncluded = 1) then 0 else 1 end)
      loop
         if (v_nCurrentMID != r.mid)
         then
            v_nCurrentMID := r.mid;
            appendToClob (v_lData, v_vBuffer, '"MID'||to_char(r.mid)||'_INSTRUMENT_NAME"'||v_vDelimiter);
         end if;
         
         v_vColumnValue := '"MID'||to_char(r.mid)||'T'||to_char(r.tid)||'Q'||to_char(r.qid)||'R'||to_char(r.rid)||'"';
         appendToClob (v_lData, v_vBuffer, v_vColumnValue||case when (r.rn != v_nLastRownum) then v_vDelimiter end);
      end loop;

      -- add column name header to the export clob
      appendToClob (v_lData, v_vBuffer, chr(13));

      --------------------------------------------------
      -- add data
      --------------------------------------------------
      -- Fetch rows with dbms_sql package.
      while (dbms_sql.fetch_rows (v_nCurID) > 0)
      loop
         -- demo column values and bind
         for i in 1 .. v_nColumnCount 
         loop
            -- set buffer with data
            if (i not in (v_nColumnIndex_PatientID, v_nColumnIndex_IntakeID)) 
            then
               if (v_sDescTab(i).col_type = 2)
               then
                  dbms_sql.column_value (v_nCurID, i, v_nColumnValue);
                  appendToClob (v_lData, v_vBuffer, v_nColumnValue||v_vDelimiter);
               elsif (v_sDescTab(i).col_type = 12)
               then
                  dbms_sql.column_value (v_nCurID, i, v_dColumnValue);
                  appendToClob (v_lData, v_vBuffer, '"'||to_char(v_dColumnValue, v_vDateFormat)||'"'||v_vDelimiter);
               else
                  dbms_sql.column_value (v_nCurID, i, v_vColumnValue);
                  appendToClob (v_lData, v_vBuffer, '"'||v_vColumnValue||'"'||v_vDelimiter);
               end if;
            end if;
         end loop;
         
         -- set patient_id and intake_id
         dbms_sql.column_value (v_nCurID, v_nColumnIndex_PatientID, v_vPatientID);
         dbms_sql.column_value (v_nCurID, v_nColumnIndex_IntakeID, v_nIntakeID);
         
         -- instrument data using patient_id and intake_id
         v_nCurrentMID := 0;
         for r in (select * from vw_utl_rpt_intake_response
                    where instr(v_vDataIncluded,','||mid||',') >= case when (c_nShowNotIncluded = 1) then 0 else 1 end)
         loop
            if (v_nCurrentMID != r.mid)
            then
               v_nCurrentMID := r.mid;
               appendToClob (v_lData, v_vBuffer, '"'||r.module_desc||'"'||v_vDelimiter);
            end if;
            
            -- get intake response value
            if (instr(v_vDataIncluded,','||r.mid||',') > 0)
            then
               v_vColumnValue := responseValue (v_vPatientID, v_nIntakeID, r.mid, r.tid, r.qid, r.rid);
            else
               v_vColumnValue := null;
            end if;

            v_vColumnValue := replace(v_vColumnValue, '"', '""');
            appendToClob (v_lData, v_vBuffer, '"'||v_vColumnValue||'"'||case when (r.rn != v_nLastRownum) then v_vDelimiter end);
         end loop;
         
         -- add row data to the export clob
         appendToClob (v_lData, v_vBuffer, chr(13));
      end loop;

      -- add remaining text
      v_lData := v_lData||v_vBuffer;

      -- add data
      v_vSql := 'update exp_statistical_rpt set status = 2, end_date = sysdate, file_data = :P0 where request_id = :P1 and status = 1';
      execute immediate v_vSql using v_lData, pi_nRequestID;
      commit;

      begin dbms_sql.close_cursor (v_nCurID); exception when others then null; end;
      begin close rc; exception when others then null; end;
      
   exception
      when others
      then
        v_vMsg := sqlerrm;
        
         -- log job failed (-1)
         v_vSql := 'update exp_statistical_rpt set status = -1, end_date = sysdate, status_comment = :P0 where request_id = :P1';
         execute immediate v_vSql using v_vMsg, pi_nRequestID;
         commit;
   end;

   /*Run export*/
   procedure runExport (
      pi_vSessionID                     in varchar2,
      pi_vSessionClientIP               in varchar2,
      pi_nUserID                        in number,
      pi_nRequestID                     in number,
      pi_vKey                           in varchar2,
      po_nStatusCode                   out number,
      po_vStatusComment                out varchar2
      )
   is
      v_nJobID                             number;
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';
      
      v_vSql := 'Pck_Utl_Export_Data.generateCsv('||pi_nRequestID||','''||pi_vKey||''');';
      sys.dbms_job.submit(job => v_nJobID, what => v_vSql, next_date => sysdate);
      commit;
      
   exception
      when others 
      then
         po_nStatusCode := 1;
         po_vStatusComment := 'PCK_UTL_EXPORT_DATA.runExport(): '||sqlErrm;
   end;
   
   /*Cancel export*/
   procedure cancelExport (
      pi_vSessionID                     in varchar2,
      pi_vSessionClientIP               in varchar2,
      pi_nUserID                        in number,
      pi_nRequestID                     in number,
      po_nStatusCode                   out number,
      po_vStatusComment                out varchar2
      )
   is
      v_vSql                               varchar2(4000);
   begin
      po_nStatusCode    := 0; --0 = success
      po_vStatusComment := '';

      -- set status
      v_vSql := 'update exp_statistical_rpt set status = 3 where request_id = :P1 and status = 1';
      execute immediate v_vSql using pi_nRequestID;
      commit;
      
   exception
      when no_data_found 
      then
         po_nStatusCode := 1;
         po_vStatusComment := 'PCK_UTL_EXPORT_DATA.cancelExport(): '||'Export request does not exist!';
      when others 
      then
         po_nStatusCode := 1;
         po_vStatusComment := 'PCK_UTL_EXPORT_DATA.cancelExport(): '||sqlErrm;
   end;

end;
/

prompt
prompt Creating package body PCK_XFER
prompt ==============================
prompt
CREATE OR REPLACE PACKAGE BODY TBICDS.PCK_XFER IS
/* Copyright 2015 Intellica Corporation 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*transfer a patient admission to the central database*/
procedure XferPatientVisit(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      
      pi_vVisitID               in number,
      pi_nVisitLocationID       in number,
      pi_vVisitLocationName     in varchar2,
      pi_vVisitTimeStamp        in varchar2,
      pi_vVisitStatus           in varchar2,           
      pi_vVisitType             in varchar2,               
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2)
  is

    v_vSQLInsert constant varchar2(4000) :=
       'insert into
        patient_visit( REGION_ID,
                       SITE_ID,
                       DFN,
                          
                       VISIT_ID,
                       VISIT_LOCATION_ID,
                       VISIT_LOCATION_NAME,
                       VISIT_TIMESTAMP,
                       VISIT_STATUS,
                       VISIT_TYPE,
                       VISIT_DATETIME
                          )
          values(:REGION_ID,
                 :SITE_ID,
                 :DFN,
                 
                 :VISIT_ID,
                 :VISIT_LOCATION_ID,
                 :VISIT_LOCATION_NAME,
                 :VISIT_TIMESTAMP,
                 :VISIT_STATUS,
                 :VISIT_TYPE,
                 :VISIT_DATETIME)';

     --todo:
     v_vSQLUpdate constant varchar2(4000) := '';
     
     v_vSQLCount varchar2(4000) := '';
     v_nCount number := 0;

  begin

     v_nCount := 0;
     po_nStatusCode    := 0;
     po_vStatusComment := '';
     
     --check that a record exisits
     select count(*) into v_nCount 
     from patient_visit 
    WHERE region_id =  pi_nRegionID
     and site_id = pi_nSiteID
     and DFN = pi_vDFN
     and VISIT_LOCATION_ID = pi_nVisitLocationID
     and VISIT_TIMESTAMP = pi_vVisitTimeStamp;
          
     --insert if the record is not there
     if (v_nCount < 1) then

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLInsert
        USING pi_nRegionID,
              pi_nSiteID,
              pi_vDFN,
              
              pi_vVisitID,
              pi_nVisitLocationID,
              pi_vVisitLocationName,
              pi_vVisitTimeStamp,
              pi_vVisitStatus,           
              pi_vVisitType,
              to_date(pi_vVisitTimeStamp, 'yyyymmdd.hh24miss');   
                 
        commit;

      else

        --no update just insert
        commit;

      end if;

exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nStatus_Error;
      po_vStatusComment := '';

end;


/*transfer a patient admission to the central database*/
procedure XferPatientAdmission(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      
      pi_nAdmitLocationID       in number,
      pi_vAdmitLocationName     in varchar2,
      pi_vAdmitType             in varchar2,
      pi_vAdmitTimeStamp        in varchar2,
      pi_vDischargeTimeStamp   in varchar2,                          
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2)
  is

    v_vSQLInsert constant varchar2(4000) :=
       'insert into
        patient_admission( REGION_ID,
                           SITE_ID,
                           DFN,
                          
                           ADMIT_LOCATION_ID,
                           ADMIT_LOCATION_NAME,
                           ADMIT_TYPE,
                           ADMIT_TIMESTAMP,
                           ADMIT_DISCHARGE_TIMESTAMP,
                           ADMIT_DATETIME
                          )
          values(:REGION_ID,
                 :SITE_ID,
                 :DFN,
                 
                 :ADMIT_LOCATION_ID,
                 :ADMIT_LOCATION_NAME,
                 :ADMIT_TYPE,
                 :ADMIT_TIMESTAMP,
                 :ADMIT_DISCHARGE_TIMESTAMP,
                 :ADMIT_DATETIME)';

     --todo:
     v_vSQLUpdate constant varchar2(4000) := '';
    

     v_vSQLCount varchar2(4000) := '';
     v_nCount number := 0;

  begin

     v_nCount := 0;
     po_nStatusCode    := 0;
     po_vStatusComment := '';
     
     --check that a record exisits
     select count(*) into v_nCount 
     from patient_admission 
     WHERE region_id = pi_nRegionID 
      and site_id = pi_nSiteID 
      and DFN = pi_vDFN 
      and ADMIT_LOCATION_ID = pi_nAdmitLocationID 
      and ADMIT_TIMESTAMP = pi_vAdmitTimeStamp; 
     
     --insert if the record is not there
     if (v_nCount < 1) then

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLInsert
        USING pi_nRegionID,
              pi_nSiteID,
              pi_vDFN,
              
              pi_nAdmitLocationID,
              pi_vAdmitLocationName,
              pi_vAdmitType,
              pi_vAdmitTimeStamp,
              pi_vDischargeTimeStamp,
              to_date(pi_vAdmitTimeStamp, 'yyyymmdd.hh24miss');  
                 
        commit;

      else

        --execute the sql with bind vars
        --todo:
        --EXECUTE IMMEDIATE v_vSQLUpdate
        --USING pi_vRegionName,
        --      pi_nXferSystemID,
        --      pi_nRegionID;
        commit;

      end if;

exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nStatus_Error;
      po_vStatusComment := '';

end;

/*transfers a patient consult to the central database*/
procedure XferPatientConsult(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vDFN                   in varchar2,
      
      pi_vConsultID             in varchar2,
      pi_vConsultTimeStamp      in varchar2,
      pi_vConsultStatus         in varchar2,
      pi_vConsultTitle          in varchar2,
      pi_vConsultText           in varchar2,                          
      
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2)
  is

    v_vSQLInsert constant varchar2(4000) :=
         'insert into
          patient_consult( REGION_ID,
                           SITE_ID,
                           DFN,
                          
                           CONSULT_ID,
                           CONSULT_TIMESTAMP,
                           CONSULT_STATUS,
                           CONSULT_TITLE,
                           CONSULT_TEXT,
                           CONSULT_DATETIME
                          )
          values(:REGION_ID,
                 :SITE_ID,
                 :DFN,
                 
                 :CONSULT_ID,
                 :CONSULT_TIMESTAMP,
                 :CONSULT_STATUS,
                 :CONSULT_TITLE,
                 :CONSULT_TEXT,
                 :CONSULT_DATETIME)';

     --todo:
     v_vSQLUpdate constant varchar2(4000) := '';
     
     v_vSQLCount varchar2(4000) := '';
     v_nCount number := 0;

  begin

     v_nCount := 0;
     po_nStatusCode    := 0;
     po_vStatusComment := '';
     
     --check that a record exisits
     select count(*) into v_nCount  
     from patient_consult 
     WHERE region_id = pi_nRegionID 
      and site_id = pi_nSiteID 
      and DFN = pi_vDFN 
      and consult_id = pi_vConsultID;
     
     --insert if the record is not there
     if (v_nCount < 1) then

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLInsert
        USING pi_nRegionID,
              pi_nSiteID,
              pi_vDFN,
              
              pi_vConsultID,
              pi_vConsultTimeStamp,
              pi_vConsultStatus,
              pi_vConsultTitle,
              pi_vConsultText,
              to_date(pi_vConsultTimeStamp, 'yyyymmdd.hh24miss');                 
        commit;

      else

        --execute the sql with bind vars
        --todo:
        --EXECUTE IMMEDIATE v_vSQLUpdate
        --USING pi_vRegionName,
        --      pi_nXferSystemID,
        --      pi_nRegionID;
        commit;

      end if;

exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nStatus_Error;
      po_vStatusComment := '';

end;

/*transfers a patient appointment to the database*/
procedure XferPatientAppointment(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vAppointmentID         in varchar2,
      pi_vDFN                   in varchar2,
      pi_nApptClinicID          in number,
      pi_nApptSiteID            in number,
      pi_vApptCurrentStatus     in varchar2,
      pi_vApptPurpose           in varchar2,
      pi_vApptStatus            in varchar2,
      pi_vApptText              in varchar2,
      pi_vApptTimeStamp         in varchar2,
      pi_vApptTitle             in varchar2,
      pi_vApptType              in varchar2,
      pi_vApptVisitID           in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2)
  is

    v_vSQLInsert constant varchar2(4000) :=
         'insert into
          patient_appointment( REGION_ID,
                               SITE_ID,
                               APPT_ID,
                               DFN,
                               APPT_CLINIC_ID,
                               APPT_SITE_ID,
                               APPT_CURRENT_STATUS,
                               APPT_PURPOSE,
                               APPT_STATUS,
                               APPT_TEXT,
                               APPT_TIMESTAMP,
                               APPT_TITLE,
                               APPT_TYPE,
                               APPT_VISIT_ID,
                               APPT_DATETIME
                             )
          values(:REGION_ID,
                 :SITE_ID,
                 :APPT_ID,
                 :DFN,
                 :APPT_CLINIC_ID,
                 :APPT_SITE_ID,
                 :APPT_CURRENT_STATUS,
                 :APPT_PURPOSE,
                 :APPT_STATUS,
                 :APPT_TEXT,
                 :APPT_TIMESTAMP,
                 :APPT_TITLE,
                 :APPT_TYPE,
                 :APPT_VISIT_ID,
                 :APPT_DATETIME)';

     --todo:
     v_vSQLUpdate constant varchar2(4000) := '';
     
     v_vSQLCount varchar2(4000) := '';
     v_nCount number := 0;

  begin

     v_nCount := 0;
     po_nStatusCode    := 0;
     po_vStatusComment := '';
     
     --check that a record exisits
     select count(*) into v_nCount  
     from patient_appointment 
     WHERE region_id = pi_nRegionID 
      and site_id = pi_nSiteID 
      and DFN = pi_vDFN 
      and appt_id = pi_vAppointmentID;     
  
     --insert if the record is not there
     if (v_nCount < 1) then

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLInsert
        USING pi_nRegionID,
              pi_nSiteID,
              pi_vAppointmentID,
              pi_vDFN,
              pi_nApptClinicID,
              pi_nApptSiteID,
              pi_vApptCurrentStatus,
              pi_vApptPurpose,
              pi_vApptStatus,
              pi_vApptText,
              pi_vApptTimeStamp,
              pi_vApptTitle,
              pi_vApptType,
              pi_vApptVisitID,
              to_date(pi_vApptTimeStamp, 'yyyymmdd.hh24miss');
                 
        commit;

      else

        --execute the sql with bind vars
        --todo:
        --EXECUTE IMMEDIATE v_vSQLUpdate
        --USING pi_vRegionName,
        --      pi_nXferSystemID,
        --      pi_nRegionID;
        commit;

      end if;

exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nStatus_Error;
      po_vStatusComment := '';

end;

/*
transfers a clinic to the database
*/
procedure XferClinic(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_nClinicID              in number,
      pi_vClinicLabel           in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2)
  is

    v_vSQLInsert constant varchar2(4000) :=
         'insert into
          tbicds.utl_Clinic(Clinic_id,
                               Clinic_label,
                               xfer_system_id,
                               xfer_date,
                               region_id,
                               site_id
                          )
          values(:Clinic_ID,
                 :Clinic_LABEL,
                 :XFER_SYSTEM_ID,
                 sysdate,
                 :REGION_ID,
                 :SITE_ID)';

     v_vSQLUpdate constant varchar2(4000) :=
         'update tbicds.utl_Clinic
          set Clinic_label = :Clinic_LABEL,
              xfer_system_id = :XFER_SYSTEM_ID,
              xfer_date = sysdate
          where Clinic_id = :Clinic_ID
           and region_id = :REGION_ID
           and site_id = :SITE_ID';

     v_vSQLCount varchar2(4000) := '';
     v_nCount number := 0;

  begin

     --error messages
     v_nCount := 0;
     po_nStatusCode    := 0;
     po_vStatusComment := '';
     
     --check that a record exisits
     select count(*) into v_nCount 
     from tbicds.utl_Clinic 
     WHERE clinic_id = pi_nClinicID 
      and region_id = pi_nRegionID 
      and site_id = pi_nSiteID;

     --insert if the record is not there
     if (v_nCount < 1) then

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLInsert
        USING pi_nClinicID,
              pi_vClinicLabel,
              pi_nXferSystemID,
              pi_nRegionID,
              pi_nSiteID;
        commit;

      else

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLUpdate
        USING pi_vClinicLabel,
              pi_nXferSystemID,
              pi_nClinicID,
              pi_nRegionID,
              pi_nSiteID;

        commit;

      end if;

exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nStatus_Error;
      po_vStatusComment := 'Error transferring clinic';
      
end;

/*Transfers a note title from an external source such as MDWS to the database
*/
procedure XferNoteTitle(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_nNoteTitleTag          in number,
      pi_vNoteTitleLabel        in varchar2,
      pi_nIsConsult             in number,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2)
  is

    v_vSQLInsert constant varchar2(4000) :=
         'insert into
          tbicds.utl_note_title(note_title_tag,
                               note_title_label,
                               xfer_system_id,
                               xfer_date,
                               region_id,
                               site_id,
                               is_consult
                          )
          values(:note_title_tag,
                 :NOTE_TITLE_LABEL,
                 :XFER_SYSTEM_ID,
                 sysdate,
                 :REGION_ID,
                 :SITE_ID,
                 :IS_CONSULT)';

     v_vSQLUpdate constant varchar2(4000) :=
         'update tbicds.utl_note_title
          set note_title_tag = :NOTE_TITLE_TAG,
              xfer_system_id = :XFER_SYSTEM_ID,
              xfer_date = sysdate,
              is_consult = :IS_CONSULT
          where note_title_label = :NOTE_TITLE_LABEL
          and  region_id = :REGION_ID
          and  site_id = :SITE_ID';

     v_vSQLCount varchar2(4000) := '';
     v_nCount number := 0;

  begin

     v_nCount := 0;
     po_nStatusCode    := 0;
     po_vStatusComment := '';
     
     --check that a record exisits
     select count(*) into v_nCount 
     from tbicds.utl_note_title
     WHERE note_title_label = pi_vNoteTitleLabel
      and site_id = pi_nSiteID
      and region_id = pi_nRegionID;
     
     --insert if the record is not there, otherwise update
     if (v_nCount < 1) then

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLInsert
        USING pi_nNoteTitleTag,
              pi_vNoteTitleLabel,
              pi_nXferSystemID,
              pi_nRegionID,
              pi_nSiteID,
              pi_nIsConsult;
        commit;

      else

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLUpdate
        USING pi_nNoteTitleTag,
              pi_nXferSystemID,
              pi_nIsConsult,
              pi_vNoteTitleLabel,
              pi_nRegionID,
              pi_nSiteID;
        commit;

      end if;

exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nStatus_Error;
      po_vStatusComment := 'Error transferring note title';
     
end;

/*
Transfers a region from an external source such as MDWS to the database
*/
procedure XferRegion(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_vRegionName            in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2)
  is

    v_vSQLInsert constant varchar2(4000) :=
         'insert into
          utl_region( region_id,
                             region_name,
                             xfer_system_id,
                             xfer_date
                          )
          values(:region_id,
                 :region_name,
                 :xfer_system_id,
                 sysdate)';

     v_vSQLUpdate constant varchar2(4000) :=
         'update utl_region
          set region_name = :region_name,
              xfer_system_id = :XFER_SYSTEM_ID,
              xfer_date = sysdate
          where region_id = :region_id';

     v_vSQLCount varchar2(4000) := '';
     v_nCount number := 0;

  begin

     v_nCount := 0;
     po_nStatusCode    := 0;
     po_vStatusComment := '';
     
     --check that a record exisits
     select count(*) into v_nCount 
     from utl_region  
     WHERE region_id = pi_nRegionID;
     
     --insert if the record is not there
     if (v_nCount < 1) then

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLInsert
        USING pi_nRegionID,
              pi_vRegionName,
              pi_nXferSystemID;
        commit;

      else

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLUpdate
        USING pi_vRegionName,
              pi_nXferSystemID,
              pi_nRegionID;
        commit;

      end if;

exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nStatus_Error;
      po_vStatusComment := '';

end;

/*
Transfers a site from an external source such as MDWS to the database
*/
procedure XferSite(
      pi_vSessionID             in varchar2,
      pi_vSessionClientIP       in varchar2,
      pi_nUserID                in number,
      pi_nXferSystemID          in number,
      pi_nRegionID              in number,
      pi_nSiteID                in number,
      pi_vSiteName            in varchar2,
      po_nStatusCode            out number,
      po_vStatusComment         out varchar2)
  is

    v_vSQLInsert constant varchar2(4000) :=
         'insert into
          utl_site( region_id,
                           site_id,
                           site_name,
                           xfer_system_id,
                           xfer_date
                          )
          values(:region_id,
                 :site_id,
                 :site_name,
                 :xfer_system_id,
                 sysdate)';

     v_vSQLUpdate constant varchar2(4000) :=
         'update utl_site
          set site_name = :site_name,
              xfer_system_id = :XFER_SYSTEM_ID,
              xfer_date = sysdate
          where region_id = :region_id
            and site_id = :site_id';

     v_vSQLCount varchar2(4000) := '';
     v_nCount number := 0;

  begin

     v_nCount := 0;
     po_nStatusCode    := 0;
     po_vStatusComment := '';
     
     --check that a record exisits
     select count(*) into v_nCount 
     from utl_site 
     WHERE region_id = pi_nRegionID 
      AND site_id = pi_nSiteID;

     --insert if the record is not there
     if (v_nCount < 1) then

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLInsert
        USING pi_nRegionID,
              pi_nSiteID,
              pi_vSiteName,
              pi_nXferSystemID;
        commit;

      else

        --execute the sql with bind vars
        EXECUTE IMMEDIATE v_vSQLUpdate
        USING pi_vSiteName,
              pi_nXferSystemID,
              pi_nRegionID,
              pi_nSiteID;
        commit;

      end if;

exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nStatus_Error;
      po_vStatusComment := '';
 
end;


/*
Transfers a user from an external source such as MDWS to the database
*/
procedure XferUser(
      pi_vSessionID           in varchar2,
      pi_vSessionClientIP     in varchar2,
      pi_nUserID              in number,
      pi_nXferSystemID        in number,
      pi_vDUZ                 in varchar2,
      pi_vLastName            in varchar2,
      pi_vFirstName           in varchar2,
      pi_vFirstLastName       in varchar2, 
      pi_vGreeting            in varchar2,
      pi_vTitle               in varchar2,
      pi_nRegionID            in number,
      pi_nSiteID              in number,
      pi_vUserClass           in varchar2,
      po_nUserID              out number,
      po_nStatusCode          out number,
      po_vStatusComment       out varchar2)
 is

    v_vSQLFXUserInsert constant varchar2(4000) :=
         'insert into
          fx_user( fx_user_id,
                   duz,
                   region_id,
                   site_id,
                   greeting,
                   xfer_system_id,
                   xfer_date)
          values(:fx_user_id,
                 :duz,
                 :region_id,
                 :site_id,
                 :greeting,
                 :xfer_system_id,
                 sysdate)';
      
      --insert statement for app_user table
      --todo: work out DMIS
      v_vSQLSuatUserInsert constant varchar2(4000) :=
         'insert into
          app_user( email,
                     uidpwd,
                     rank,
                     name,
                     title,
                     provider_id,
                     military_service_id,
                     corps,
                     unit,
                     squadron,
                     phone,
                     dims_id,
                     entry_date,
                     locked,
                     must_change_password,
                     fx_user_id,
                     supervisor_id,
                     graph_pref,
                     xfer_system_id,
                     xfer_date)
          values('''',
                 ''N/A'',
                 ''N/A'',
                 :name,
                 :title,
                 :provider_id,
                 0,
                 ''N/A'',
                 ''N/A'',
                 ''N/A'',
                 '''',
                 ''0000'', 
                 sysdate,
                 0,
                 0,
                 :fx_user_id,
                 ''N/A'',
                 0,
                 :xfer_system_id,
                 sysdate)';

     --fx_user update
     v_vSQLFXUserUpdate constant varchar2(4000) :=
         'update fx_user
          set duz = :duz,
              region_id = :region_id,
              site_id = :site_id,
              greeting = :greeting,
              xfer_system_id = :xfer_system_id,
              xfer_date =  sysdate
          where fx_user_id = :fx_user_id';

     --app_user update
     v_vSQLSuatUserUpdate constant varchar2(4000) :=
         'update app_user
          set name = :name,
              title = :title,
              xfer_system_id = :XFER_SYSTEM_ID,
              xfer_date = sysdate
          where fx_user_id = :fx_user_id';
          
     v_nCount number := 0;
     v_nFXUserID number := 0;
    
  begin

     po_nStatusCode    := 0;
     po_vStatusComment := '';
     
     --check that a record exisits
     select count(*) into v_nCount
     from fx_user t
     where t.region_id = pi_nRegionID
     and t.site_id = pi_nSiteID
     and t.duz = pi_vDUZ;
     
     --insert if the record is not there
     if (v_nCount < 1) then
        
        --get a new fx_user_id for this user
        select seqfxuserid.nextval into v_nFXUserID from dual;

        --execute fx_user insert sql with bind vars
        EXECUTE IMMEDIATE v_vSQLFXUserInsert
        USING v_nFXUserID,
              pi_vDUZ,
              pi_nRegionID,
              pi_nSiteID,
              pi_vGreeting,
              pi_nXferSystemID;
        
        --execute the app_user insert sql with bind vars
        EXECUTE IMMEDIATE v_vSQLSuatUserInsert
        USING pi_vFirstLastName,
              pi_vTitle,
              PCK_SYSTEM_ID.GetNewProviderID(pi_vFirstName,
                                             pi_vLastName),
              v_nFXUserID,
              pi_nXferSystemID;
                      
        --load user rights, todo: research this some may 
        --want to pass the rights in?
        insert into fx_user_rights(fx_user_id,
                                   user_rights,
                                   read_only,
                                   user_type)
        values( v_nFXUserID,             
                65204351,
                0,
                1);
        
        commit;
        --keep the user id
        po_nUserID := v_nFXUserID;

      else
        
        --get the fx_user_id for the update
        select fx_user_id into v_nFXUserID
        from fx_user t
        where t.region_id = pi_nRegionID
        and t.site_id = pi_nSiteID
        and t.duz = pi_vDUZ;

        --execute the fx_user sql with bind vars 
        EXECUTE IMMEDIATE v_vSQLFXUserUpdate
        USING pi_vDUZ,
              pi_nRegionID,
              pi_nSiteID,
              pi_vGreeting,
              pi_nXferSystemID,
              v_nFXUserID;
        
        --execute the app_user sql with bind vars        
        EXECUTE IMMEDIATE v_vSQLSuatUserUpdate
        USING pi_vFirstLastName,
              pi_vTitle,
              pi_nXferSystemID,
              v_nFXUserID;
        
        commit;
     
        --keep the user id
        po_nUserID := v_nFXUserID;
        
      end if;

exception
    when others then
      rollback;
      po_nStatusCode    := PCK_COMMON.c_nStatus_Error;
      po_vStatusComment := '';
 
end;


/*Transfers a patient from an external source such as MDWS to the database
*/
procedure XferPatient (   pi_vSessionID        in varchar2,
                          pi_vSessionClientIP  in varchar2,
                          pi_nUserID           in number,
                          pi_nXferSystemID     in number,
                          pi_vKey              in varchar2,
                          pi_nRegionID         in number,
                          pi_nSiteID           in number,
                          pi_vMDWSPatientID              in varchar2,
                          pi_vSSN              in varchar2,
                          pi_dtDOB             in date,
                          pi_vFirstName        in varchar2,
                          pi_vFullName         in varchar2,
                          pi_vLastName         in varchar2,
                          pi_vMI               in varchar2,
                          pi_nSex              in number,
                          pi_vHomeAddr1        in varchar2,
                          pi_vHomeAddr2        in varchar2,
                          pi_vHomeCity         in varchar2,
                          pi_vHomeState        in varchar2,
                          pi_vHomeZip          in varchar2,
                          pi_vHomePhone        in varchar2,
                          po_vPatientID        out varchar2,
                          po_nStatusCode       out number,
                          po_vStatusComment    out varchar2
                       )
is

   v_nRelationshipID number := 0;
   v_nCount number := 0;
   v_vSQLCount varchar2(2000) := '';
   v_vSex varchar2(20) := '';
   v_vProviderID varchar2(255) := '';
   
   --get the patient id and encounter id from an sp call
   v_vPatientID varchar2(500) := '';
   v_vEncounterID varchar2(500) := '';
   
begin
  
    po_vPatientID := '';
    po_nStatusCode    := 0;
    po_vStatusComment := '';
    v_nCount := 0;
    v_vSQLCount := '';
    v_vSex := 'U';
    v_vProviderID := '';
    v_nRelationshipID := 0;

    --get count
    SELECT count(*) into v_nCount 
      FROM patient_demographics 
     WHERE DFN = pi_vMDWSPatientID
       and region_id = pi_nRegionID
       and site_id = pi_nSiteID;

    --translate gender
    if(pi_nSex = 1) then
      v_vSex := 'M';
    end if;
    if(pi_nSex = 2) then
      v_vSex := 'F';
    end if;

    --default the provider to the person logged in
    select t.provider_id into v_vProviderID
    from app_user t
    where t.fx_user_id = pi_nuserid;

    if(v_nCount < 1) then
    
        --get a new patient id by calling the PCK_SYSTEM_ID package 
        v_vPatientID := PCK_SYSTEM_ID.GetNewPatientID(pi_vFirstName,
                                                      pi_vLastName,
                                                      to_char(pi_dtdob,'mm/dd/yyyy'),
                                                      v_vSex,
                                                      pi_vSSN);
                                                      
                                                      

        --insert new record into the patient demographics table
        insert into patient_demographics( patient_id,
                                          dfn,
                                          region_id,
                                          site_id,
                                          first_name,
                                          last_name,
                                          mi,
                                          ssn,
                                          gender,
                                          dob,
                                          provider_id)
        values
        (
           upper(v_vPatientID),
           pi_vMDWSPatientID,
           pi_nRegionID,
           pi_nSiteID,
           fnc_utl_encstr(upper(pi_vFirstName), pi_vKey, upper(v_vPatientID)),
           fnc_utl_encstr(upper(pi_vLastName), pi_vKey, upper(v_vPatientID)),
           fnc_utl_encstr(upper(pi_vMI), pi_vKey, upper(v_vPatientID)),
           fnc_utl_encstr(upper(pi_vSSN), pi_vKey, upper(v_vPatientID)),
           fnc_utl_encstr(v_vSex, pi_vKey, upper(v_vPatientID)),
           fnc_utl_encstr(to_char(pi_dtdob,'mm/dd/yyyy'), pi_vKey, upper(v_vPatientID)),
           v_vProviderID
        );
        commit;
        
        --pass the patient id back to the caller
        po_vPatientID := v_vPatientID;                        

        --Create Initial Patient Sponsor Record Needed By Assessments --Assessments can only to Updates
        /*insert into patient_sponsor
          (patient_id, relationship_id, last_updated, last_updated_by)
        values
          (v_vPatientID, v_nRelationshipID, sysdate, pi_nUserID);
        commit;*/

        --Create Initial Emergency Contact Record Needed By Assessments --Assessments can only to Updates
        insert into patient_emergency_contact
          (patient_id, relationship_id, last_updated, last_updated_by)
        values
          (v_vPatientID, v_nRelationshipID, sysdate, pi_nUserID);
        commit;

        --insert a new treatment record
 --       insert into treatment
 --         (treatment_id,
 --          patient_id,
 --          initial_visit_date,
 --          last_updated,
 --          last_updated_by)
 --       values
 --         (1, v_vPatientID, sysdate, sysdate, pi_nUserID);
 --       commit;

        --add all the events
        /*pck_patient_events.addallevents(pi_vSessionID,
                                        pi_vSessionClientIP,
                                        pi_nUserID,
                                        v_vPatientID,
                                        po_nStatusCode,
                                        po_vStatusComment);*/

        --insert patient step
        /*PCK_PATIENT_TX_STEP.InsertPatientStep(pi_vSessionID,
                                              pi_vSessionClientIP,
                                              pi_nUserID,
                                              v_vPatientID,
                                              0,
                                              po_nStatusCode,
                                              po_vStatusComment);*/

       --assign assessments
       /*PCK_INTAKE.AssignInitialAssessments(pi_vSessionID,
                                              pi_vSessionClientIP,
                                              pi_nUserID,
                                              v_vPatientID,
                                              po_nStatusCode,
                                              po_vStatusComment);*/
   else
                                              
       select t.patient_id into v_vPatientID 
       from patient_demographics t   
       where t.region_id = pi_nRegionID 
       and t.site_id = pi_nSiteID 
       and t.dfn = pi_vMDWSPatientID;
   
        --pass the patient id back to the caller
        po_vPatientID := v_vPatientID;    
        
        --todo: not updating the patients record at this time                                                                                
        null;

   end if;

exception
    when others then
      po_nStatusCode    := PCK_COMMON.c_nStatus_Error;
      po_vStatusComment := '';
end;
      
END;
/

prompt
prompt Creating type body TYP_OBJ_RPT_CDE_PAT
prompt ======================================
prompt
create or replace type body tbicds.TYP_OBJ_RPT_CDE_PAT as

   constructor function TYP_OBJ_RPT_CDE_PAT
      return self as result
   is
   begin
      return;
   end;
   
   member procedure setValue (
      pi_nIndex                         in number,
      pi_vValue                         in varchar2
      )
   is
   begin
      if (pi_nIndex = 1) then self.c1 := pi_vValue;
      elsif (pi_nIndex = 2) then self.c2 := pi_vValue;
      elsif (pi_nIndex = 3) then self.c3 := pi_vValue;
      elsif (pi_nIndex = 4) then self.c4 := pi_vValue;
      elsif (pi_nIndex = 5) then self.c5 := pi_vValue;
      elsif (pi_nIndex = 6) then self.c6 := pi_vValue;
      elsif (pi_nIndex = 7) then self.c7 := pi_vValue;
      elsif (pi_nIndex = 8) then self.c8 := pi_vValue;
      elsif (pi_nIndex = 9) then self.c9 := pi_vValue;
      elsif (pi_nIndex = 10) then self.c10 := pi_vValue;
      elsif (pi_nIndex = 11) then self.c11 := pi_vValue;
      elsif (pi_nIndex = 12) then self.c12 := pi_vValue;
      elsif (pi_nIndex = 13) then self.c13 := pi_vValue;
      elsif (pi_nIndex = 14) then self.c14 := pi_vValue;
      elsif (pi_nIndex = 15) then self.c15 := pi_vValue;
      elsif (pi_nIndex = 16) then self.c16 := pi_vValue;
      elsif (pi_nIndex = 17) then self.c17 := pi_vValue;
      elsif (pi_nIndex = 18) then self.c18 := pi_vValue;
      elsif (pi_nIndex = 19) then self.c19 := pi_vValue;
      elsif (pi_nIndex = 20) then self.c20 := pi_vValue;
      elsif (pi_nIndex = 21) then self.c21 := pi_vValue;
      elsif (pi_nIndex = 22) then self.c22 := pi_vValue;
      elsif (pi_nIndex = 23) then self.c23 := pi_vValue;
      elsif (pi_nIndex = 24) then self.c24 := pi_vValue;
      elsif (pi_nIndex = 25) then self.c25 := pi_vValue;
      elsif (pi_nIndex = 26) then self.c26 := pi_vValue;
      elsif (pi_nIndex = 27) then self.c27 := pi_vValue;
      elsif (pi_nIndex = 28) then self.c28 := pi_vValue;
      elsif (pi_nIndex = 29) then self.c29 := pi_vValue;
      elsif (pi_nIndex = 30) then self.c30 := pi_vValue;
      elsif (pi_nIndex = 31) then self.c31 := pi_vValue;
      elsif (pi_nIndex = 32) then self.c32 := pi_vValue;
      elsif (pi_nIndex = 33) then self.c33 := pi_vValue;
      elsif (pi_nIndex = 34) then self.c34 := pi_vValue;
      elsif (pi_nIndex = 35) then self.c35 := pi_vValue;
      elsif (pi_nIndex = 36) then self.c36 := pi_vValue;
      elsif (pi_nIndex = 37) then self.c37 := pi_vValue;
      elsif (pi_nIndex = 38) then self.c38 := pi_vValue;
      elsif (pi_nIndex = 39) then self.c39 := pi_vValue;
      elsif (pi_nIndex = 40) then self.c40 := pi_vValue;
      elsif (pi_nIndex = 41) then self.c41 := pi_vValue;
      elsif (pi_nIndex = 42) then self.c42 := pi_vValue;
      elsif (pi_nIndex = 43) then self.c43 := pi_vValue;
      elsif (pi_nIndex = 44) then self.c44 := pi_vValue;
      elsif (pi_nIndex = 45) then self.c45 := pi_vValue;
      elsif (pi_nIndex = 46) then self.c46 := pi_vValue;
      elsif (pi_nIndex = 47) then self.c47 := pi_vValue;
      elsif (pi_nIndex = 48) then self.c48 := pi_vValue;
      elsif (pi_nIndex = 49) then self.c49 := pi_vValue;
      elsif (pi_nIndex = 50) then self.c50 := pi_vValue;
      elsif (pi_nIndex = 51) then self.c51 := pi_vValue;
      elsif (pi_nIndex = 52) then self.c52 := pi_vValue;
      elsif (pi_nIndex = 53) then self.c53 := pi_vValue;
      elsif (pi_nIndex = 54) then self.c54 := pi_vValue;
      elsif (pi_nIndex = 55) then self.c55 := pi_vValue;
      elsif (pi_nIndex = 56) then self.c56 := pi_vValue;
      elsif (pi_nIndex = 57) then self.c57 := pi_vValue;
      elsif (pi_nIndex = 58) then self.c58 := pi_vValue;
      elsif (pi_nIndex = 59) then self.c59 := pi_vValue;
      elsif (pi_nIndex = 60) then self.c60 := pi_vValue;
      elsif (pi_nIndex = 61) then self.c61 := pi_vValue;
      elsif (pi_nIndex = 62) then self.c62 := pi_vValue;
      elsif (pi_nIndex = 63) then self.c63 := pi_vValue;
      elsif (pi_nIndex = 64) then self.c64 := pi_vValue;
      elsif (pi_nIndex = 65) then self.c65 := pi_vValue;
      elsif (pi_nIndex = 66) then self.c66 := pi_vValue;
      elsif (pi_nIndex = 67) then self.c67 := pi_vValue;
      elsif (pi_nIndex = 68) then self.c68 := pi_vValue;
      elsif (pi_nIndex = 69) then self.c69 := pi_vValue;
      elsif (pi_nIndex = 70) then self.c70 := pi_vValue;
      elsif (pi_nIndex = 71) then self.c71 := pi_vValue;
      elsif (pi_nIndex = 72) then self.c72 := pi_vValue;
      elsif (pi_nIndex = 73) then self.c73 := pi_vValue;
      elsif (pi_nIndex = 74) then self.c74 := pi_vValue;
      elsif (pi_nIndex = 75) then self.c75 := pi_vValue;
      elsif (pi_nIndex = 76) then self.c76 := pi_vValue;
      elsif (pi_nIndex = 77) then self.c77 := pi_vValue;
      elsif (pi_nIndex = 78) then self.c78 := pi_vValue;
      elsif (pi_nIndex = 79) then self.c79 := pi_vValue;
      elsif (pi_nIndex = 80) then self.c80 := pi_vValue;
      elsif (pi_nIndex = 81) then self.c81 := pi_vValue;
      elsif (pi_nIndex = 82) then self.c82 := pi_vValue;
      elsif (pi_nIndex = 83) then self.c83 := pi_vValue;
      elsif (pi_nIndex = 84) then self.c84 := pi_vValue;
      elsif (pi_nIndex = 85) then self.c85 := pi_vValue;
      elsif (pi_nIndex = 86) then self.c86 := pi_vValue;
      elsif (pi_nIndex = 87) then self.c87 := pi_vValue;
      elsif (pi_nIndex = 88) then self.c88 := pi_vValue;
      elsif (pi_nIndex = 89) then self.c89 := pi_vValue;
      elsif (pi_nIndex = 90) then self.c90 := pi_vValue;
      elsif (pi_nIndex = 91) then self.c91 := pi_vValue;
      elsif (pi_nIndex = 92) then self.c92 := pi_vValue;
      elsif (pi_nIndex = 93) then self.c93 := pi_vValue;
      elsif (pi_nIndex = 94) then self.c94 := pi_vValue;
      elsif (pi_nIndex = 95) then self.c95 := pi_vValue;
      elsif (pi_nIndex = 96) then self.c96 := pi_vValue;
      elsif (pi_nIndex = 97) then self.c97 := pi_vValue;
      elsif (pi_nIndex = 98) then self.c98 := pi_vValue;
      elsif (pi_nIndex = 99) then self.c99 := pi_vValue;
      elsif (pi_nIndex = 100) then self.c100 := pi_vValue;
      elsif (pi_nIndex = 101) then self.c101 := pi_vValue;
      elsif (pi_nIndex = 102) then self.c102 := pi_vValue;
      elsif (pi_nIndex = 103) then self.c103 := pi_vValue;
      elsif (pi_nIndex = 104) then self.c104 := pi_vValue;
      elsif (pi_nIndex = 105) then self.c105 := pi_vValue;
      elsif (pi_nIndex = 106) then self.c106 := pi_vValue;
      elsif (pi_nIndex = 107) then self.c107 := pi_vValue;
      elsif (pi_nIndex = 108) then self.c108 := pi_vValue;
      elsif (pi_nIndex = 109) then self.c109 := pi_vValue;
      elsif (pi_nIndex = 110) then self.c110 := pi_vValue;
      elsif (pi_nIndex = 111) then self.c111 := pi_vValue;
      elsif (pi_nIndex = 112) then self.c112 := pi_vValue;
      elsif (pi_nIndex = 113) then self.c113 := pi_vValue;
      elsif (pi_nIndex = 114) then self.c114 := pi_vValue;
      elsif (pi_nIndex = 115) then self.c115 := pi_vValue;
      elsif (pi_nIndex = 116) then self.c116 := pi_vValue;
      elsif (pi_nIndex = 117) then self.c117 := pi_vValue;
      elsif (pi_nIndex = 118) then self.c118 := pi_vValue;
      elsif (pi_nIndex = 119) then self.c119 := pi_vValue;
      elsif (pi_nIndex = 120) then self.c120 := pi_vValue;
      elsif (pi_nIndex = 121) then self.c121 := pi_vValue;
      elsif (pi_nIndex = 122) then self.c122 := pi_vValue;
      elsif (pi_nIndex = 123) then self.c123 := pi_vValue;
      elsif (pi_nIndex = 124) then self.c124 := pi_vValue;
      elsif (pi_nIndex = 125) then self.c125 := pi_vValue;
      elsif (pi_nIndex = 126) then self.c126 := pi_vValue;
      elsif (pi_nIndex = 127) then self.c127 := pi_vValue;
      elsif (pi_nIndex = 128) then self.c128 := pi_vValue;
      elsif (pi_nIndex = 129) then self.c129 := pi_vValue;
      elsif (pi_nIndex = 130) then self.c130 := pi_vValue;
      elsif (pi_nIndex = 131) then self.c131 := pi_vValue;
      elsif (pi_nIndex = 132) then self.c132 := pi_vValue;
      elsif (pi_nIndex = 133) then self.c133 := pi_vValue;
      elsif (pi_nIndex = 134) then self.c134 := pi_vValue;
      elsif (pi_nIndex = 135) then self.c135 := pi_vValue;
      elsif (pi_nIndex = 136) then self.c136 := pi_vValue;
      elsif (pi_nIndex = 137) then self.c137 := pi_vValue;
      elsif (pi_nIndex = 138) then self.c138 := pi_vValue;
      elsif (pi_nIndex = 139) then self.c139 := pi_vValue;
      elsif (pi_nIndex = 140) then self.c140 := pi_vValue;
      elsif (pi_nIndex = 141) then self.c141 := pi_vValue;
      elsif (pi_nIndex = 142) then self.c142 := pi_vValue;
      elsif (pi_nIndex = 143) then self.c143 := pi_vValue;
      elsif (pi_nIndex = 144) then self.c144 := pi_vValue;
      elsif (pi_nIndex = 145) then self.c145 := pi_vValue;
      elsif (pi_nIndex = 146) then self.c146 := pi_vValue;
      elsif (pi_nIndex = 147) then self.c147 := pi_vValue;
      elsif (pi_nIndex = 148) then self.c148 := pi_vValue;
      elsif (pi_nIndex = 149) then self.c149 := pi_vValue;
      elsif (pi_nIndex = 150) then self.c150 := pi_vValue;
      elsif (pi_nIndex = 151) then self.c151 := pi_vValue;
      elsif (pi_nIndex = 152) then self.c152 := pi_vValue;
      elsif (pi_nIndex = 153) then self.c153 := pi_vValue;
      elsif (pi_nIndex = 154) then self.c154 := pi_vValue;
      elsif (pi_nIndex = 155) then self.c155 := pi_vValue;
      elsif (pi_nIndex = 156) then self.c156 := pi_vValue;
      elsif (pi_nIndex = 157) then self.c157 := pi_vValue;
      elsif (pi_nIndex = 158) then self.c158 := pi_vValue;
      elsif (pi_nIndex = 159) then self.c159 := pi_vValue;
      elsif (pi_nIndex = 160) then self.c160 := pi_vValue;
      elsif (pi_nIndex = 161) then self.c161 := pi_vValue;
      elsif (pi_nIndex = 162) then self.c162 := pi_vValue;
      elsif (pi_nIndex = 163) then self.c163 := pi_vValue;
      elsif (pi_nIndex = 164) then self.c164 := pi_vValue;
      elsif (pi_nIndex = 165) then self.c165 := pi_vValue;
      elsif (pi_nIndex = 166) then self.c166 := pi_vValue;
      elsif (pi_nIndex = 167) then self.c167 := pi_vValue;
      elsif (pi_nIndex = 168) then self.c168 := pi_vValue;
      elsif (pi_nIndex = 169) then self.c169 := pi_vValue;
      elsif (pi_nIndex = 170) then self.c170 := pi_vValue;
      elsif (pi_nIndex = 171) then self.c171 := pi_vValue;
      elsif (pi_nIndex = 172) then self.c172 := pi_vValue;
      elsif (pi_nIndex = 173) then self.c173 := pi_vValue;
      elsif (pi_nIndex = 174) then self.c174 := pi_vValue;
      elsif (pi_nIndex = 175) then self.c175 := pi_vValue;
      elsif (pi_nIndex = 176) then self.c176 := pi_vValue;
      elsif (pi_nIndex = 177) then self.c177 := pi_vValue;
      elsif (pi_nIndex = 178) then self.c178 := pi_vValue;
      elsif (pi_nIndex = 179) then self.c179 := pi_vValue;
      elsif (pi_nIndex = 180) then self.c180 := pi_vValue;
      elsif (pi_nIndex = 181) then self.c181 := pi_vValue;
      elsif (pi_nIndex = 182) then self.c182 := pi_vValue;
      elsif (pi_nIndex = 183) then self.c183 := pi_vValue;
      elsif (pi_nIndex = 184) then self.c184 := pi_vValue;
      elsif (pi_nIndex = 185) then self.c185 := pi_vValue;
      elsif (pi_nIndex = 186) then self.c186 := pi_vValue;
      elsif (pi_nIndex = 187) then self.c187 := pi_vValue;
      elsif (pi_nIndex = 188) then self.c188 := pi_vValue;
      elsif (pi_nIndex = 189) then self.c189 := pi_vValue;
      elsif (pi_nIndex = 190) then self.c190 := pi_vValue;
      elsif (pi_nIndex = 191) then self.c191 := pi_vValue;
      elsif (pi_nIndex = 192) then self.c192 := pi_vValue;
      elsif (pi_nIndex = 193) then self.c193 := pi_vValue;
      elsif (pi_nIndex = 194) then self.c194 := pi_vValue;
      elsif (pi_nIndex = 195) then self.c195 := pi_vValue;
      elsif (pi_nIndex = 196) then self.c196 := pi_vValue;
      elsif (pi_nIndex = 197) then self.c197 := pi_vValue;
      elsif (pi_nIndex = 198) then self.c198 := pi_vValue;
      elsif (pi_nIndex = 199) then self.c199 := pi_vValue;
      elsif (pi_nIndex = 200) then self.c200 := pi_vValue;
      end if;
   exception when others then null;
   
   end;
   
end;
/